我有一个 tbl_customers
表。 (像很多人一样)
我有第二个表:tbl_customers_tags
此表只是让我为单个客户记录存储无限的关键字/标签。 这是列结构:
`tbl_customers_tags`
+-------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------------+------+-----+---------+----------------+
| ID | int(11) unsigned | NO | PRI | NULL | auto_increment |
| customerid | int(11) unsigned | NO | MUL | NULL | |
| tagid | mediumint(5)unsigned| NO | | NULL | |
因此,我现在需要提取一些报告,方法是查找具有特定标签标识符的任何客户记录。我得到重复。 这是我当前的查询语句:
SELECT c.firstname, c.lastname, c.datecreated
FROM `tbl_customers` c
LEFT JOIN `tbl_customers_tags` ctags ON c.customerid = ctags.customerid
WHERE ctags.tagid IN(2,3,15)
当单个 customerid
关联到多个 tagid
记录时,有没有办法不返回重复项?
最佳答案
试试这个
SELECT c.firstname, c.lastname, c.datecreated
FROM 'tbl_customers' c
where exists
( select 'x' from tbl_customers_tags where customerid = c.customerid and
tagid IN(2,3,15)
)
如果您只对在标签表中有记录的客户感兴趣,为什么不进行全联接而不是左联接?
关于MySQL - 一对多连接语句返回重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14185606/