ホームページ  >  記事  >  バックエンド開発  >  複数テーブルクエリのSQL文

複数テーブルクエリのSQL文

WBOY
WBOYオリジナル
2016-06-13 13:50:071155ブラウズ

複数テーブル クエリの 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 フィールドでは、%$kw% のようなすべてのレコードが取得され、mtime に従ってソートされます。

取得したレコードで保持する必要があるフィールドには、a(b)id、title、cid、content、および mtime が含まれます。

SQL コード
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->
$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 を見てみましょう。

2 つの 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
声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。