我有一个表客户,存储有customer_id,电子邮件和参考。还有一个附加表customer_data,用于存储对客户所做的更改的历史记录,即,当发生更改时,将插入新行。
为了在一个表中显示客户信息,需要将两个表连接起来,但是只有customer_data中的最新行才应该连接到客户表中。
由于查询是分页的,因此变得有点复杂,因此具有限制和偏移量。
我该如何使用MySQL?我想我想在某个地方放一个DISTINCT …
此刻的查询是这样的-
SELECT *, CONCAT(title,' ',forename,' ',surname) AS name FROM customer c INNER JOIN customer_data d on c.customer_id=d.customer_id WHERE name LIKE '%Smith%' LIMIT 10, 20
另外,我是否认为可以通过这种方式将CONCAT与LIKE一起使用?
(我很欣赏INNER JOIN可能是错误的JOIN类型。实际上我不知道不同的JOIN之间有什么区别。我现在要研究一下!)
您可能需要尝试以下方法:
SELECT CONCAT(title, ' ', forename, ' ', surname) AS name FROM customer c JOIN ( SELECT MAX(id) max_id, customer_id FROM customer_data GROUP BY customer_id ) c_max ON (c_max.customer_id = c.customer_id) JOIN customer_data cd ON (cd.id = c_max.max_id) WHERE CONCAT(title, ' ', forename, ' ', surname) LIKE '%Smith%' LIMIT 10, 20;
请注意,a JOIN只是的同义词INNER JOIN。
JOIN
INNER JOIN
测试用例:
CREATE TABLE customer (customer_id int); CREATE TABLE customer_data ( id int, customer_id int, title varchar(10), forename varchar(10), surname varchar(10) ); INSERT INTO customer VALUES (1); INSERT INTO customer VALUES (2); INSERT INTO customer VALUES (3); INSERT INTO customer_data VALUES (1, 1, 'Mr', 'Bobby', 'Smith'); INSERT INTO customer_data VALUES (2, 1, 'Mr', 'Bob', 'Smith'); INSERT INTO customer_data VALUES (3, 2, 'Mr', 'Jane', 'Green'); INSERT INTO customer_data VALUES (4, 2, 'Miss', 'Jane', 'Green'); INSERT INTO customer_data VALUES (5, 3, 'Dr', 'Jack', 'Black');
结果(不含LIMIT和的查询WHERE):
LIMIT
WHERE
SELECT CONCAT(title, ' ', forename, ' ', surname) AS name FROM customer c JOIN ( SELECT MAX(id) max_id, customer_id FROM customer_data GROUP BY customer_id ) c_max ON (c_max.customer_id = c.customer_id) JOIN customer_data cd ON (cd.id = c_max.max_id); +-----------------+ | name | +-----------------+ | Mr Bob Smith | | Miss Jane Green | | Dr Jack Black | +-----------------+ 3 rows in set (0.00 sec)