简体   繁体   中英

How to return a multi select sql query with a few joins in a flat row

I'm trying to return a list of user types by postcode area. For example I have a column "membertype" which may be X, Y or Z. In the postcode area G83 I may have multiple type X and multiple type Y. I'm looking to return a result like the following

| postcode | X | Y |

| G83 | 9 | 3 |

Trying this for now

SELECT substring(postcode, 1, locate (' ', postcode) - 1) AS postcode, count(u.membertype) AS cook, count(u2.membertype) AS customer FROM user_locations AS ul
LEFT JOIN users AS u ON u.id = ul.user_id
LEFT JOIN users AS u2 ON u2.id = ul.user_id
WHERE u.membertype = "seller"
OR u2.membertype = "customer"
GROUP BY postcode

I'd like a response that I can loop through to output a table in my app.

You can use FIELDS TERMINATED BY':

SELECT substring(postcode, 1, locate (' ', postcode) - 1) AS postcode, count(u.membertype) AS cook, count(u2.membertype) AS customer FROM user_locations AS ul
LEFT JOIN users AS u ON u.id = ul.user_id
LEFT JOIN users AS u2 ON u2.id = ul.user_id
WHERE u.membertype = "seller"
OR u2.membertype = "customer"
GROUP BY postcode
INTO OUTFILE '/var/lib/mysql-files/files.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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