Multi-table query SQL statements

Source: Internet
Author: User
For A multi-table query, the 10 fields in SQL statement A are aid, title, cid, content, atime, aorder, acount, a1, a2, in the mtimeB table, the nine fields are bid, title, cid, content, btime, border, b3, b4, and mtime. now I obtain an SQL statement for multi-table queries.
10 fields in Table
The fields are aid, title, cid, content, atime, aorder, acount, a1, a2, and mtime.

9 fields in Table B
The fields are bid, title, cid, content, btime, border, b3, b4, and mtime.

Now I get A keyword $ kw. I need to search for the title fields of Table A and Table B at the same time, get all records of like % $ kw %, and sort them by mtime.

The fields to be retained in the obtained records include a (B) id, title, cid, content, and mtime.

SQL code
  $sql = 'SELECT ';$sql .= 'A.aid as id,B.bid AS id,';$sql .= 'A.title as title,B.title as title,';$sql .= 'A.cid as cid,B.cid as cid,';$sql .= 'A.content as content,B.content as content,';$sql .= 'A.mtime as mtime,B.mtime as mtime';$sql .= 'FROM A,B WHERE title like "%'.$kw.'%" ORDER BY mtime DESC';


Is it feasible to construct an SQL statement like this?

If not, how can I write this SQL statement?

------ Solution --------------------
Let's take a look at union.

Two select statements use union in the middle, and the fields after the select statement must be the same.

Select a. id, a. xxx from a where a. title like '% $ km %'
Union
Select B. id, B. xxx from B where B. title like '% $ km %'
------ Solution --------------------
Select aid, title, cid, content, mtime from a where title like '% km %'
Order by mtime desc

Union all

Select bid, title, cid, content, mtime from B where title like '% km %'
Order by mtime desc

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.