2013-07-31 39 views
2

我有兩個表像如何獲取記錄在有條件的表中兩個表 - PHP和MySQL

table: t1 
id|name|type 
1 | a |0 
2 | b |1 
3 | c |0 
4 | d |0 
... 

table: t2 
uid|type 
4 |1 
3 |0 
... 

我想計數或獲得表t1記錄有型= 1和記錄有ID = UID表t2了type = 1
什麼是計算或獲取記錄在一個查詢像

$type = 1; 
$count = mysql_num_rows(mysql_query("Select * .... Where type = $type ")); //$count = 2 
$result = mysql_query("Select * ... order by id desc "); // $result include record in table t1 has id (4, 2) b/c order by id desc 

編輯的最佳方式: 我做了一個sql嘗試在http://www.sqlfiddle.com/#!2/8847d1/12 但我不能這樣做
我想記錄的結果看起來像(全列有我的上述條件)

id|name| 
4 |d | 
2 |b | 

如何做到這一點感謝

+0

這些表是鏈接的,即有主鍵和外鍵嗎? – jeff

+0

@jeff我在做直接,我不使用外鍵 – freestyle

回答

1
select t1.id,t1.name from t1 left join t2 on t1.id = t2.uid where t1.type = 1 or t2.type = 1 
+0

這是不正確的:( – freestyle

+0

你能解釋爲什麼它不正確@freestyle –

+0

結果是0記錄。我認爲@jeff理解我的問題,但他的代碼不起作用當我從t1選擇*時:| – freestyle

0

試試這個

select * from t1 join t2 on t1.id = t2.uid where t1.type = 1 and t2.type = 1 

閱讀如何使用連接(左連接,右Ĵ OIN,加入)

1. read here

2. 2nd docs

+0

我想你不明白我的問題。我做你的代碼,但沒有記錄如果表t1沒有type = 1; :( – freestyle

1

既然有可以使用UNION查詢表之間沒有聯繫:關於工會加入更多信息

SELECT id,type FROM t1 WHERE type=1 
UNION 
SELECT uid AS id,type FROM t2 WHERE type=1 

http://dev.mysql.com/doc/refman/5.0/en/union.html

+0

我嘗試選擇所有像:SELECT * FROM t1 WHERE type = 1 UNION SELECT uid AS id,type FROM t2 WHERE type = 1 order by id desc .But它不工作:( – freestyle

+0

這不適用於選擇所有PLZ請參閱我的代碼http://www.sqlfiddle.com/#!2/8847d1/12 – freestyle

+0

兩個SELECT中的字段必須匹配字段數量和字段名稱本身,這就是爲什麼「uid as id」第二選擇語句 – jeff

0
$type = 1; 
if (isset($type) and $type > 0) 
{ 
    $sql = "SELECT id, name FROM t1 
      LEFT JOIN t2 ON t1.id = t2.uid 
      WHERE t1.type = $type AND t2.type = $type 
      ORDER BY t1.id DESC"; 
    $count = mysql_num_rows($sql) or die('Error'); 
    $result = mysql_query($sql) or die('Error'); 
} 
相關問題