2016-07-26 75 views
2

我目前有三個表:的MySQL/MariaDB的 - 通過查詢參考表表搜索

desc products; 
+----------------+-------------------+------+-----+---------+----------------+ 
| Field   | Type    | Null | Key | Default | Extra   | 
+----------------+-------------------+------+-----+---------+----------------+ 
| id    | int(255) unsigned | NO | PRI | NULL | auto_increment | 
| name   | text    | NO |  | NULL |    | 
| desc_short  | text    | NO |  | NULL |    | 
+----------------+-------------------+------+-----+---------+----------------+ 

desc tags; 
+------------+-------------------+------+-----+---------+----------------+ 
| Field  | Type    | Null | Key | Default | Extra   | 
+------------+-------------------+------+-----+---------+----------------+ 
| id   | int(255) unsigned | NO | PRI | NULL | auto_increment | 
| tag  | varchar(255)  | YES | UNI | NULL |    | 
| iscategory | tinyint(4)  | NO |  | 0  |    | 
+------------+-------------------+------+-----+---------+----------------+ 

desc products_tags; 
+------------+-------------------+------+-----+---------+-------+ 
| Field  | Type    | Null | Key | Default | Extra | 
+------------+-------------------+------+-----+---------+-------+ 
| product_id | int(255) unsigned | YES | MUL | NULL |  | 
| tag_id  | int(255) unsigned | YES | MUL | NULL |  | 
+------------+-------------------+------+-----+---------+-------+ 

products_tags實際上是我已經與創建參考表:

CREATE TABLE product_tags (
    product_id INT(255) UNSIGNED, 
    tag_id INT(255) UNSIGNED, 
    CONSTRAINT fk_products_id FOREIGN KEY (tag_id) REFERENCES tags(id) ON DELETE CASCADE ON UPDATE CASCADE, 
    CONSTRAINT fk_tag_id FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE ON UPDATE CASCADE 
); 

我試圖通過搜索相應的標籤來篩選表格產品中的項目。 我已經找到了一些similar problems,但我無法讓它正常工作....

非常感謝提前。

+0

請在MySQL閱讀文檔。 Foreignkey引用不會自動連接相關的表。您必須使用JOIN啓用實際關係。 – mootmoot

回答

0

嘗試這個連接查詢:

SELECT p.id, p.name, p.desc_short 
FROM products p 
INNER JOIN products_tag pt 
    ON p.id = pt.product_id 
INNER JOIN tags t 
    ON t.id = pt.tag_id 
WHERE t.tag = 'some tag' 
+0

非常感謝,確實有效。 你能告訴我爲什麼我必須寫p。*,我通常把表名稱。 (在其他例子中,我首先讓我困惑)。 – derped

+1

@derped:當連接發生時,必須告訴mysql EXPLICIT目標表名和列名。因爲表名可能很長,我們可以用短別名替換它(即'FROM product p'或更具體的'FROM product'p'') – mootmoot