简体   繁体   English

2表上的MySQL内部联接不起作用

[英]Mysql inner join on 2 tables don't work

I have a table in my database named contacts and a table named views. 我的数据库中有一个名为contacts的表,一个名为views的表。

On the table contacts I have the following fields: 在表格联系人上,我具有以下字段:

  • id ID
  • status 状态
  • first_name 名字
  • last_name

The status can be cold, prospect or lost. 状态可以是冷,潜在或丢失。

On the table views I have the following fields: 在表视图上,我具有以下字段:

  • user_id 用户身份
  • art_views art_views
  • art_title art_title

The relation between those 2 tables is id and user_id. 这两个表之间的关系是id和user_id。

I need a query to make a new html table with the following columns: 我需要一个查询来创建具有以下各列的新html表:

  • art_title art_title
  • cold
  • prospect 展望
  • lost 丢失

Now I have the following query (UPDATED): 现在,我有以下查询(已更新):

SELECT
v.art_title,
SUM(CASE c.status WHEN 'cold' THEN v.art_views ELSE 0 END) cold,
SUM(CASE c.status WHEN 'prospect' THEN v.art_views ELSE 0 END) prospect,
SUM(CASE c.status WHEN 'lost' THEN v.art_views ELSE 0 END) lost
FROM views v
JOIN contacts c ON v.user_id = c.id
GROUP BY v.art_title

This query is working now (thanks to Gerv) but i still have users who don't have a status. 该查询现在正在工作(感谢Gerv),但是我仍然有没有状态的用户。 So i leave the field user_id in the table 'views' empty. 因此,我将表“视图”中的字段user_id留空。 How can i change the query for those users so i can count them also? 我如何更改这些用户的查询,以便我也可以计算它们?

I tried to: SUM(CASE v.user_id WHEN ' ' THEN v.art_views ELSE 0 END) test, but with no result here. 我尝试:SUM(CASE v.user_id WHEN''THEN v.art_views ELSE 0 END)测试,但这里没有结果。

You can switch the logic by selecting from the views table and joining de contacts table. 您可以通过从视图表中选择并加入联系表来切换逻辑。 Below query will pivot the status with a CASE clause 下面的查询将使用CASE子句来确定状态

SELECT
    v.art_title,
    SUM(CASE c.status WHEN 'cold' THEN v.art_views ELSE 0 END) cold,
    SUM(CASE c.status WHEN 'prospect' THEN v.art_views ELSE 0 END) prospect,
    SUM(CASE c.status WHEN 'lost' THEN v.art_views ELSE 0 END) lost,
    SUM(CASE c.status WHEN NULL THEN v.art_views ELSE 0 END) no_user
FROM views v
LEFT JOIN contacts c ON v.user_id = c.id
GROUP BY v.art_title
ORDER BY (cold+lost+prospect+no_user) DESC
LIMIT 10

尝试

SELECT art_title, SUM(art_views), status FROM contacts AS c INNER JOIN views AS v ON v.user_id = c.id GROUP BY v.art_title, c.status

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM