多表查詢的sql語句

來源:互聯網
上載者:User
求一個多表查詢的sql語句
A表10個欄位
欄位分別為aid, title, cid, content, atime, aorder, acount,a1, a2, mtime

B表9個欄位
欄位分別為bid, title, cid, content, btime, border, b3, b4, mtime

現在我擷取到一個關鍵詞$kw,我需要同時搜尋A表和B表的title欄位,擷取到所有like %$kw%的所有記錄,並根據mtime來排序。

擷取的記錄裡,需要保留的欄位有a(b)id,title,cid,content,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';


我這樣構造sql,可行嗎?

如果不可行,那麼怎麼寫這個sql語句呢?

------解決方案--------------------
去看一下 union

兩個 select 然後中間用一下 union , 要求 select 後面的欄位都一樣的

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%'
------解決方案--------------------
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
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.