I'm trying to display a list of books from a table (books) but I want to display the name of the book in green if the user connected added the book in his collection. The collections are in the table collection. So I need to retrieve all the informations from the books table but I need to differentiate the books owned by the user.
I tried something like this :
SELECT * FROM books LEFT JOIN collection ON books.ID = collection.ID_book AND collection.ID_member = :ID_member WHERE books.ID_author = :ID_author
:ID_member is the ID in session of the member logged in and ID_author is the name of the author I want to display the list. But with that query, I cannot retrieve the ID of books that the user doesn't own. Do you have an idea to retrieve these ID too ?
I thought of a second query inside the while() but that would means a query PER book...
EDIT (more informations) :
I have a table books with all the informations concerning the books.
Then, I have a table collection with these columns : ID, ID_member, ID_book
With my query, if I want to display all books from... let's say Stephen King, I have something like this :
book || ID of the book || book owned by the user
1 || 1 || 0
2 || 2 || 0
3 || || 1
4 || 4 || 0
5 || || 1
6 || 6 || 0
The ID I want to display is the collection.ID_book because if I display ID, it will show collection.ID
So as you can see when the user own the book I can't have the ID of the book... but I can display the other informations (like the book title) because the other informations are taken from the books table and the ID from the collection table... Too bad that it's not possible to chose the table in the
I understand that the problem is that the ID column exists in both tables. One solution may be to duplicate the ID column, like ID2. Then it will work because ID2 doesn't exist in the collection table. But that is maybe too much...
Thank you for your help.
Regards.
It is very easy to set columns up with aliases:
SELECT books.ID AS book_id, collections.id AS collection_id
FROM books
LEFT JOIN collection ON books.ID = collection.ID_book AND collection.ID_member = :ID_member
WHERE books.ID_author = :ID_author
After you have done this your column names will be book_id and collection_id and since they are no longer duplicate names (with one overwriting the other) you can access each of them.
Then if you know that you want all the columns from books but only the idcolumn from collection you can do something like this:
SELECT books.*, collections.id AS collection_id
FROM books
LEFT JOIN collection ON books.ID = collection.ID_book AND collection.ID_member = :ID_member
WHERE books.ID_author = :ID_author
I think your query should be doing what you want. I suspect that the problem may be the select * and multiple columns with the same name. Does this query do what you want?
SELECT b.*,
(case when c.ID_book is not null then 'GREEN' else 'NOT OWNED' end) as color
FROM books b LEFT JOIN
collection c
ON b.ID = c.ID_book AND c.ID_member = :ID_member
WHERE b.ID_author = :ID_author;
I think you can solve this problem by changing your query slightly, maybe give this a try.
SELECT * FROM books
LEFT JOIN collection ON books.ID = collection.ID_book
WHERE books.ID_author = :ID_author OR collection.ID_member = :ID_member
When joining on the condition of the user id, you're only going to have those rows available in the result set. By moving that condition to the WHERE clause using the OR operator, you can have both conditions met.
NOTE: Try not to use SELECT *.
SELECT * FROM books LEFT JOIN collection
ON books.ID = collection.ID_book
INNER JOIN member ON collection.ID_member = member.:ID_member WHERE books.ID_author = :ID_author
would you try that sir.. I'm not sure though. I'm assuming that the ID_member fields came from a member table.. and the ID_member to collection table is a foreign key..
Related
I have two tables.
One table has everything I need including a cardId(PK)
The other name is a user type table. This table stores the userId and the cardId(FK).
SELECT ci.cardId, ci.year, ci.name, ci.number
FROM USERCARDS uc
INNER JOIN CARDINDEX ci ON uc.cardId = ci.cardId
WHERE uc.userId = 'USER_ID'
So for this query, it will display the cardId, year, name, and number from the CARDINDEX. It will only display the cards that the user has saved in USERCARDS.
I want to do the opposite. If a user is looking at, lets just say, 5 cards, but the CARDINDEX has 50 cards, this query will display the information for the five cards. However, for a new query, I would want to show the remaining 45 cards. Basically, they cant add a card they already are following.
I tried to have uc.cardId != ci.cardId but that didn't work. Im kind of lost.
You can phrase this as a LEFT JOIN:
SELECT ci.cardId, ci.year, ci.name, ci.number
FROM CARDINDEX ci LEFT JOIN
USERCARDS uc
ON uc.cardId = ci.cardId AND
uc.userId = 'USER_ID'
WHERE uc.cardID IS NULL;
Alternatively, you could write this using `NOT EXISTS:
SELECT ci.cardId, ci.year, ci.name, ci.number
FROM CARDINDEX ci
WHERE NOT EXISTS (SELECT 1
FROM USERCARDS uc
WHERE uc.cardId = ci.cardId AND
uc.userId = 'USER_ID'
);
I have two tables, one for registered users and one to store votes.
We are logging in with registrants.id and registrants.zipcode. Once they vote their votes are inserted into the votes table, along with their Registration ID.
Im trying to right a select statement that returns a record that will select all the records for Matched ID and Zipcode, but the ID is not in the Votes.voter column. i have tried all kinds of variations of all the joins i can think of. is it something simple i am missing.
SELECT * FROM registrants
LEFT JOIN votes on registrants.id = votes.voter
WHERE registrants.id = 1 AND registrants.zipcode = 46706 and votes.voter <> 1
Perhaps a not exists query:
select * from registrants
where registrants.zipcode = '46706'
and not exists (select 1 from votes where registrants.id = votes.voter)
I'll try to be right to the point. Here's what I'm trying to do.
I have two tables that I need to pull data from:
membershipstable = || groupid || templateid || userid
|| 2 || 1 || 0
|| 0 || 1 || 3
|| 2 || 0 || 4
userstable = || id || firstname || lastname || email
What I would like to do would be something like:
SELECT * FROM userstable WHERE id = userid (in memberships table) -- AND/OR -- WHERE id = userid IF groupid is associated with templateid, and templateid is equal to $currenttemplateid
Or in human speak: Look at the memberships table and if you find a row containing a templateid that matches $currenttemplateid then bring back the userid from that row. Then, look at the userstable and retrieve the information for each user who has an id matching a userid we found above. Also, if you find any rows that contain a templateid that matches $currenttemplateid, then look at the groupid in that row and bring back any userid that is in any row with that groupid, and again retrieve the information for any user with an id that matches the userid that was found above.
I'm sorry if my explanation is somewhat confusing, and if my question reeks of newbishness (also, don't worry, I'm not using unprepared statements in the actual project)... I know that this can be done with MySQL in a single, efficient, and beautiful query but I'm at a complete loss as to what exactly that query would look like... Thank you very much for your help. :)
Use a 3-way join to find all the users in the same group as the selected member.
SELECT u.*
FROM usertable AS u
JOIN membershiptable AS m1 ON u.id = m1.userid
JOIN membershiptable AS m2 ON m1.groupid = m2.groupid
WHERE m2.templateid = $currenttemplateid
DEMO
For anyone who may come looking for the answer at a later time, there is the concern of ending up with duplicate entries in the return if a user has been assigned to both a template and a group that is also assigned to the template. A solution for this is to put DISTINCT directly after the SELECT portion of the query. E.g.
$query = "
SELECT DISTINCT
u.id,
u.firstname,
u.lastname,
u.username,
u.email
FROM $userstable AS u
INNER JOIN $membershipstable AS M1 ON u.id = M1.userid
INNER JOIN $membershipstable AS M2 ON M1.groupid = M2.groupid
WHERE M2.templateid = :currenttemplateid
";
This returns only non duplicate results.
I have 2 tables.
Table A: trades: which contains the columns: tradeID, tradeName, tradeShow, and tradeGuy.
Table B: offers: which contains the columns: tradeID, offerName, offerGuy.
I'm trying to select all columns from table A (trades) WHERE the value of "tradeShow" = 'Yes', And the value of "tradeGuy" != the user's Username. That much is easy, but I also don't want to select any records which have an offer created by the user. In other words, in table B (offers), offerGuy != Username WHERE trade ID from Table B = tradeID from Table A.
But, how do I merge these 2 conditions? I've tried this:
$sql = "SELECT *
FROM trades t1
JOIN offers t2
ON (t1.tradeID = t2.tradeID)
WHERE t1.tradeShow='Yes' AND t1.tradeGuy!='$username' AND t2.offeringGuy!='$username'";
But the problem with that is it only selects the records from trades which have an offer, because of the forth line: ON (t1.tradeID = t2.tradeID), as in it only selects trades which have a record in (offers) that mentions their tradeID.
I've also tried an awkward attempt to link the 2 tables with a meaningless link by adding a "linker" column to each table with the default value of "XXX", and did this:
$sql = "SELECT *
FROM trades t1
JOIN offers t2
ON (t1.linkerA = t2.linkerB)
WHERE t1.tradeShow='Yes' AND t1.tradeGuy!='$username' AND (t2.offeringGuy!='$username' WHERE t1.tradeID=t2.tradeID)";
But the problem with that is using 2 Where clauses...
So, how do I merge the 2 conditions?
What you're looking for is called an OUTER JOIN (in this case a LEFT OUTER JOIN) which will give you null results for missing matches, something like;
SELECT *
FROM trades t1
LEFT OUTER JOIN offers t2
ON t1.tradeID = t2.tradeID AND t2.offeringGuy = '$username'
WHERE t1.tradeShow='Yes' AND t1.tradeGuy!='$username' AND t2.offeringGuy IS NULL
We add a condition to the LEFT JOIN that we're only interested in matches against t2.offeringGuy = '$username', which will return NULL values in t2's fields if there is no match.
Then we just check that t2.offeringGuy IS NULL to find the non matches.
I would do this with not exists rather than an explicit join:
SELECT *
FROM trades t
WHERE t.tradeShow = 'Yes' AND t.tradeGuy <> '$username' and
not exists (select 1
from offers o
where t.tradeID = o.tradeID and o.tradeGuy = '$username'
);
I have an instrument list and teachers instrument list.
I would like to get a full instrument list with id and name.
Then check the teachers_instrument table for their instruments and if a specific teacher has the instrument add NULL or 1 value in a new column.
I can then take this to loop over some instrument checkboxes in Codeigniter, it just seems to make more sense to pull the data as I need it from the DB but am struggling to write the query.
teaching_instrument_list
- id
- instrument_name
teachers_instruments
- id
- teacher_id
- teacher_instrument_id
SELECT
a.instrument,
a.id
FROM
teaching_instrument_list a
LEFT JOIN
(
SELECT teachers_instruments.teacher_instrument_id
FROM teachers_instruments
WHERE teacher_id = 170
) b ON a.id = b.teacher_instrument_id
my query would look like this:
instrument name id value
--------------- -- -----
woodwinds 1 if the teacher has this instrument, set 1
brass 2 0
strings 3 1
One possible approach:
SELECT i.instrument_name, COUNT(ti.teacher_id) AS used_by
FROM teaching_instrument_list AS i
LEFT JOIN teachers_instruments AS ti
ON ti.teacher_instrument_id = i.id
GROUP BY ti.teacher_instrument_id
ORDER BY i.id;
Here's SQL Fiddle (tables' naming is a bit different).
Explanation: with LEFT JOIN on instrument_id we'll get as many teacher_id values for each instrument as teachers using it are - or just a single NULL value, if none uses it. The next step is to use GROUP BY and COUNT() to, well, group the result set by instruments and count their users (excluding NULL-valued rows).
If what you want is to show all the instruments and some flag showing whether or now a teacher uses it, you need another LEFT JOIN:
SELECT i.instrument_name, NOT ISNULL(teacher_id) AS in_use
FROM teaching_instrument_list AS i
LEFT JOIN teachers_instruments AS ti
ON ti.teacher_instrument_id = i.id
AND ti.teacher_id = :teacher_id;
Demo.
Well this can be achieved like this
SELECT
id,
instrument_name,
if(ti.teacher_instrument_id IS NULL,0,1) as `Value`
from teaching_instrument_list as til
LEFT JOIN teachers_instruments as ti
on ti.teacher_instrument_id = til.id
Add a column and check for teacher_instrument_id. If found set Value to 1 else 0.