There are two tables, which can be joined, and the relationship is 1 to many. I wish the rows of results to be merged.
For example:
Table 1: contacts
.------------.----------.
| contact_id | username |
:------------+----------:
| 1 | user1 |
:------------+----------:
| 2 | user2 |
:------------+----------:
| 3 | user3 |
'------------'----------'
Table 2: documents
.-------------.------------.----------.
| document_id | contact_id | filename |
:-------------+------------+----------:
| 1 | 1 | abc.txt |
:-------------+------------+----------:
| 2 | 1 | bcd.txt |
:-------------+------------+----------:
| 3 | 1 | cde.txt |
:-------------+------------+----------:
| 4 | 2 | 123,txt |
:-------------+------------+----------:
| 5 | 2 | 234.txt |
:-------------+------------+----------:
| 6 | 3 | xyz.txt |
'-------------'------------'----------'
The result I wish I can get:
.------------.----------.---------------------------.
| contact_id | username | filenames |
:------------+----------+---------------------------:
| 1 | user1 | abc.txt, bcd.txt, cde.txt |
:------------+----------+---------------------------:
| 2 | user2 | 123.txt, 234.txt |
:------------+----------+---------------------------:
| 3 | user3 | xyz.txt |
'------------'----------'---------------------------'
Updated:
SELECT c.contact_id, c.username, GROUP_CONCAT(d.filename) as filenames
FROM contacts c
LEFT JOIN documents d
ON c.contact_id = d.contact_id
GROUP BY c.contact_id
You should really post your attempts with your question, so that we can see what you have tried. In that way, it will be easy to push you in the right direction, as well as give the rest of us the impression that you have put some effort into the matter before asking the question. Stackoverflow is not a coding service.
To answer your question,
What you would like to do in this case, is to perform an INNER JOIN on your two tables, and have the MYSQL function, GROUP_CONCAT();, in your SELECT statement.
When you look at your two tables, you have a coherent id (contact_id) that you should use in your INNER JOIN to link your two tables together.
You then, at the end, need to perform a GROUP BY to group your results accordingly, i.e. to group the results by contact_id.
Your SQL would look something like this:
SELECT
tbl_contacts.contact_id,
tbl_contacts.username,
GROUP_CONCAT(tbl_documents.filename) as file_name
FROM
tbl_contacts
INNER JOIN
tbl_documents ON tbl_contacts.contact_id = tbl_documents.contact_id
GROUP BY
tbl_contacts.contact_id
Working SQL fiddle
Related
I am trying to get values matching the value from the second column. For example, I want to know who is the sender for Bill Gates by only using IDs.
I have two tables,
*users* table
| user_ID | Full_name |
| -------- | -------------- |
| 1 | Steve Jobs |
| 2 | Bill Gates |
| 3 | Elon Musk |
*relationships* table (with both column foreign keys)
| user_sender | user_receiver |
| ------------ | -------------- |
| 1 | 2 |
| 3 | 1 |
| 3 | 2 |
I want to select based on "user_receiver" column the matching values in the column "user_sender"
For example, I want to know who is user_sender for 2
OUTPUT:
| | |
| ------------ | -------------- |
| 1 | 2 |
| 3 | 2 |
You need to join the tables and select the rows you want
you have access to all columns of both tables by addressing them with their alias
SELECT u.user_ID , u.Full_name,r.user_receiver
FROM users u JOIN
relationships r ON u.user_ID = r.user_sender
WHERE r.user_receiver = 2
If you want to look based on the name, then join the relationships to users.
SELECT
rel.user_sender
, rel.user_receiver
-- , sender.Full_name AS sender_name
-- , receiver.Full_name AS receiver_name
FROM relationships AS rel
JOIN users AS sender ON sender.user_ID = rel.user_sender
JOIN users As receiver ON receiver.user_ID = rel.user_receiver
WHERE receiver.Full_name = 'Bill Gates'
If you already know the user_receiver number, and you only want the ID's
SELECT *
FROM relationships
WHERE user_receiver = 2
I'm trying to setup a new permissions database in MySQL and I'm breaking my brain over something that I'm sure is very simple. I'm certain something to this tune has been answered here before but after hours of searching I have found nothing that works.
I have 4 tables that are relevant
Permission (contains every possible permission)
|permission_name | description |
--------------------------------
|users.list | etc. etc. |
|users.update | etc. etc. |
|users.delete | etc. etc. |
User
| id | fname | group_id |
------------------------------
| 1 | John | 1 |
| 2 | Nancy | 1 |
| 3 | Paul | 2 |
Group
| group_id | group_name |
-------------------------
| 1 | Webmasters |
| 2 | Corporate |
| 3 | HR |
Group_permission (contains permissions relevant to each group)
| group_id | permission_name | permission_type (1=Y|0=not set|-1=N)
----------------------------------------------
| 1 | users.list | 1 |
| 1 | users.update | 1 |
| 2 | users.list | 1 |
OK so lots of relations going on, but I'm trying to get ALL the group permissions for a specific user EVEN if the group permission doesn't exist yet.
I imagined this being some sort of left join using a permission table as a base, but whenever I include the WHERE user.id = 2 it limits my result set down and won't include nulls on the right side.
SELECT a.permission_name, IFNULL(b.permission_type, 0)
FROM permission a
LEFT JOIN group_permission b on b.permission_name = a.permission_name
LEFT JOIN user c on c.group_id = b.group_id
WHERE c.id = 2
the result I want to see for Nancy is
|permission_name | permission_type |
------------------------------------
|users.list | 1 |
|users.update | 0 |
|users.delete | 0 |
I won't know what group the user is in on the PHP side, so I have to query by using the users ID only.
All I'm getting is
|permission_name | permission_type |
------------------------------------
|users.list | 1 |
Any help appreciated. TIA
It ended up being just a subquery that did the trick.
SELECT a.permission_name, IFNULL(b.permission_type, 0)
FROM permission a
NATURAL LEFT JOIN
(
SELECT a.group_id, a.permission_name, a.permission_type FROM group_permission a
NATURAL LEFT JOIN users b
WHERE b.id = 2
) as b
Not 100% sure that this will work, but try joining the group_permissions table to the permissions table.
SELECT a.permission_name, IFNULL(b.permission_type, 0)
FROM group_permission a
LEFT JOIN permission b on a.permission_name = b.permission_name
LEFT JOIN user c on c.group_id = b.group_id
WHERE c.id = 2
currently i have two tables with some data. the first table has the following:
+----------------+-----------+
| name | member_id |
+----------------+-----------+
| Juice Box | 49432 |
| Rainsurge | 49631 |
| spiderpigrider | 50482 |
+----------------+-----------+
The second table has the following:
+------------+-----------+
| recruit_id | bin(refs) |
+------------+-----------+
| 49432 | 1 |
| 49631 | 1 |
| 49432 | 1 |
| 49631 | 1 |
| 49432 | 1 |
| 49631 | 1 |
| 49432 | 1 |
| 49631 | 1 |
| 49432 | 1 |
| 49631 | 1 |
+------------+-----------+
I would like to return the name, total refs and member_id/recruit_id like so (listing only users with at least 1 ref)
+------------+-----------+------------+
| recruit_id | name | total_refs |
+------------+-----------+------------+
| 49631 | Rainsurge | 5 |
| 49432 | Juice Box | 5 |
+------------+-----------+------------+
select r.recruit_id,bin(r.refs),ipb.name from refs as r
inner join syndicate_ipb.core_members as ipb on ipb.member_id=r.recruit_id;
this returned my data but obviously without a total count and repeated names/ids
select r.recruit_id,count(bin(r.refs)),ipb.name from refs as r
inner join syndicate_ipb.core_members as ipb on ipb.member_id=r.recruit_id;
this returned data with the total count of everyone but only one id/name
+------------+--------------------+-----------+
| recruit_id | count(bin(r.refs)) | name |
+------------+--------------------+-----------+
| 49432 | 10 | Juice Box |
+------------+--------------------+-----------+
this returns the data but again without a count
select distinct r.recruit_id,bin(r.refs),ipb.name from refs as r
inner join syndicate_ipb.core_members as ipb on ipb.member_id=r.recruit_id;
+------------+-------------+-----------+
| recruit_id | bin(r.refs) | name |
+------------+-------------+-----------+
| 49432 | 1 | Juice Box |
| 49631 | 1 | Rainsurge |
+------------+-------------+-----------+
Any help or guidance is greatly appreciated. I feel like i'm close here but just not competent enough with SQL to get it. thanks!
You were almost there. You just missed the GROUP BY clause at the end.
Query:
SELECT
r.recruit_id,
count(bin(r.refs)),
ipb.name
FROM refs AS r
INNER JOIN syndicate_ipb.core_members AS ipb
ON ipb.member_id = r.recruit_id
GROUP BY r.recruit_id;
Note:
If bin(refs) column always contains value 1 then actually you don't need to keep that column. In that case you can use count(*) or count(r.recruit_id) to get the count.
And if bin(refs) column contains any value then count will not give you the right answer. In that case you need to use sum like Sum( bin(refs)).
You have to use the group by clause:
select r.recruit_id, ipb.name, count(bin(refs)) as total_refs
from refs as r
inner join syndicate_ipb.core_members as ipb
on ipb.member_id=r.recruit_id
group by r.recruit_id, ipb.name
having count(bin(refs)) >= 1
This group by r.recruit_id, ipb.name will group the results and this having count(bin(refs)) >= 1 will garante that it only returns members with at least one ref
Do not only group your columns just by the ones you want. Even though MySql allows it, it is not SQL Ansi pattern and even MySql now is complying with it. Use an aggregation function grouping with your entire columns on the select statement.
SELECT ipb.*, COUNT(`r`.`recruit_id`) AS cid FROM `ipb`
INNER JOIN `r` ON `r`.`join_id` = ipb.`member_id`
GROUP BY ipb.`member_id`
I need to retrieve rows from a mysql database as follows: I have a contract table, a contract line item table, and another table called udac. I need all contracts which DO NOT have a line item record with criteria based on a relationship between contract line item and udac. If there is a better way to state this question, let me know.
Table Structures
----contract--------------------- ---contractlineitem-----------
| id | customer_id | entry_date | | id | contract_id | udac_id |
--------------------------------- ------------------------------
| 1 | 1234 | 2010-01-01 | | 1 | 1 | 5 |
| 2 | 2345 | 2016-01-31 | | 2 | 1 | 2 |
--------------------------------- | 3 | 1 | 1 |
| 4 | 2 | 4 |
| 5 | 2 | 2 |
------------------------------
---udac----------
| id | udaccode |
-----------------
| 1 | SWBL/R |
| 2 | SWBL |
| 3 | ABL/R |
| 4 | ABL |
| 5 | XRS/F |
-----------------
Given the above data, contract 2 would show up but contract 1 would not, because it has contractlineitems that point to udacs that end in /F or /R.
Here's what i have so far, but it's not correct.
SELECT c.*
FROM contract c
JOIN contractlineitem cli
ON c.id = cli.contract_id
WHERE c.entry_timestamp > '2016-01-01 00:00:00'
AND NOT EXISTS (
SELECT cli.id
FROM contractlineitem cli_i
JOIN udac u
ON cli_i.udac_id = u.id
WHERE u.udaccode LIKE '%/F' OR u.udaccode LIKE '%/R'
AND cli_i.contract_id = cli.contract_id);
Tom's comment that your WHERE clause is wrong may be the problem you are chasing. Plus, using a correlated subquery may be problematic for performance if the optimizer can't figure out a better way to do it.
Here is the better way to do it using an OUTER JOIN:
SELECT c.*
FROM contract c
JOIN contractlineitem cli
ON c.id = cli.contract_id
LEFT OUTER JOIN udac u
ON ( u.id = cli.udac_id
AND ( u.udaccode LIKE '%/F' OR u.udaccode LIKE '%/R' ) )
WHERE c.entry_timestamp > '2016-01-01 00:00:00'
AND u.id IS NULL
Try that out and see if it does what you want. The query essentially does what you stated: It tries to join to udac where the code ends in '/F' or '/R', but then it only accepts the ones where it can't find a match (u.id IS NULL).
If the same row is returned multiple times incorrectly, throw a distinct on the front.
I'm having BookTable in database (with foregin hey LibID):
| BookID | BookName | BookPrice | LibID |
-------------------------------------------
| 1 | Book_1 | 200 | 1 |
| 2 | Book_2 | 100 | 1 |
| 3 | Book_3 | 300 | 2 |
| 4 | Book_4 | 150 | 4 |
and also LibraryTable:
| LibID | LibName | LibLocation |
-----------------------------------
| 1 | Lib_1 | Loc_1 |
| 2 | Lib_2 | Loc_2 |
| 3 | Lib_3 | Loc_3 |
| 4 | Lib_4 | Loc_4 |
I need to write SQL query that will return be the info about the library and number of books for that library:
| LibID | LibName | NumberOfBooks|
------------------------------------
| 1 | Lib_1 | 2 |
| 2 | Lib_2 | 1 |
| 3 | Lib_3 | 0 |
| 4 | Lib_4 | 1 |
It should be one SQL query, probably with nested queries or joins.. Not sure how the query should look like:
SELECT L.LibID AS LibID, L.LibName AS LibName, COUNT(B) AS NumberOfBooks
FROM LibraryTable L, BookTable B
WHERE L.LibID = B.LibID
Will that work?
No, this query will not work. COUNT aggregates data, so you must explicitely tell the DBMS for which group of data you want the count. In your case this is the library (you want one result record per library).
COUNT's parameter is a column, not a table, so change this to * (i.e. count records) or a certain column (e.g. LibID).
The join syntax you are using is valid, but deprecated. Use explicit joins instead. In your case an outer join would even show libraries that have no books at all, if such is possible.
select l.libid, l.libname, count(b.libid) as numberofbooks
from librarytable l
left outer join booktable b on b.libid = l.libid
group by l.libid;
You could also do all this without a join at all and get the book count in a subquery instead. Then you wouldn't have to aggregate. That's way simpler and more readable in my opinion.
select
l.libid,
l.libname,
(select count(*) booktable b where b.libid = l.libid) as numberofbooks
from librarytable l;
SELECT lt.LibID AS LibID, lt.LibName AS LibName, count(*) AS NumberOfBooks
FROM BookTable AS bt
LEFT JOIN LibraryTable AS lt ON bt.LibID = lt.LibID
GROUP BY bt.LibID