pull data from two tables - php

I need to pull data from two tables, and it's a bit over my head :
The first tables contains a list of members (member_id, username, email ...)
The second table stores relations between members (id, member_id, friend_id)
When a member adds another member as a friend, both member_ids are stored in the second table.
Now I need to output that second table, I'd like to output usernames instead of numbers :
example :
{username corresponding to member_id} added {username corresponding to friend_id} as a friend
Can someone help with the query ?

You need to perform a double join on members
SELECT mem1.username, mem2.username
FROM members mem1
INNER JOIN relations
ON mem1.member_id = relations.member_id
INNER JOIN member mem2
ON relations.friend_id = mem2.member_id

Something like:
select tb1.username as member_name,
tb2.username as friend_name
from membertable as tb1
inner join
(
membertable as tb2,
memberrelationstable
)
on
(
tb1.member_id = memberrelationstable.member_id and
tb2.member_id = memberrelationstable.friend_id
)

This is how I would do it:
SELECT member.username AS member_username, friend.username AS friend_username
FROM relations
INNER JOIN members AS member
ON relations.member_id = member.member_id
INNER JOIN members AS friend
ON relations.friend_id = mem2.member_id
I've spaced it so that you can easily see how we're joining the members table twice, and simple giving it a different name both times.
Whenever something is followed by AS, it means that you're giving it another name. This allows you to use the same table multiple times in a single query.

Related

MYSQL PHP select the opposite of a query

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'
);

Distinct Values from MySQLi Query

I am trying to only show unique userIds (userIds are (0,1,2,3,4,5,6,7,8,9 etc...) for the query I am running. I tried using DISTINCT in my query, but it only shows me unique values of the rows that have 2 or more of the same userId.
Is there a way I can use php to only show the unique values. My weak points are arrays and it makes it more complicated because its using data from a MySQLi query.
Example right now I have with the query now (lets say its GROUP BY rentPaid DESC and the rent total is 800.00 for all users):
userID rentPaid rentMonth
2--------800.00------April
1--------500.00------April
3--------400.00------April
3--------400.00------April
1--------200.00------April
1--------100.00------April
Example desired output:
userID rentPaid rentMonth
2--------800.00------April
1--------500.00------April
3--------400.00------April
Can I do this with MYSQL because I tried DISTINCT and it wouldn't work, how about PHP?
Query:
SELECT
properties.*,
leases.*,
users.userId, users.primaryPhone,
CONCAT(users.userFirstName,' ',users.userLastName) AS user,
admins.adminName, payments.*
FROM
properties
LEFT JOIN leases ON properties.propertyId = leases.propertyId
LEFT JOIN assigned ON properties.propertyId = assigned.propertyId
LEFT JOIN admins ON assigned.adminId = admins.adminId
LEFT JOIN users ON properties.propertyId = users.propertyId
LEFT JOIN payments ON properties.propertyId = payments.propertyId
WHERE
payments.rentMonth = '$currentMonth' AND
payments.rentYear = '$currentYear'
Edit: Please excuse my formatting, this is my first post.
Edit: Added query....its long, but works lol. I only want unique userIds (no double or triple userIds etc...)
I suspect this is what you want:
SELECT userID, MAX(rentPaid) AS maxRentPaid, rentMonth
FROM yourTable
WHERE rentMonth = "April"
GROUP BY userID
ORDER BY maxRentPaid

PHP/MySQL Using multiple WHEREs in one SELECT query

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'
);

Return Ids that a user doesn't have

I have two database tables. One is egl_achievement and the other is egl_achievement_member. One just holds achievements, and the other holds members who have achievements. I'm trying to write a query that will return all achievements a member doesn't have. I thought I could use MINUS, but mysql doesn't support that.
SELECT egl_achievement.id as id FROM egl_achievement LEFT JOIN egl_achievement_member ON egl_achievement.id = egl_achievement_member.egl_achievement_id WHERE egl_achievement_member.member_id =57;
This will obviously return the ids that member 57 has, but how can I get the opposite?
You can use a subselect which contains all achievments and then just list those which are not contained:
SELECT egl_achievement.id as id
FROM egl_achievement
WHERE egl_achievement.id NOT IN(
SELECT egl_achievement_member.egl_achievement_id
FROM egl_achievement_member
WHERE egl_achievement_member.member_id =57);
You should be able to use NOT IN.
This should select all distinct id's which member 57 does not have.
select distinct eql_achievement.id as id
from eql_achievement where eql_achievement.id not in
(SELECT egl_achievement_member.eql_achievement_id as id FROM egl_achievement_member
WHERE egl_achievement_member.member_id =57;)
Right join and filter the ones without id (So those that are not defined in your A table)
SELECT * FROM `egl_achievement_member` `a`
RIGHT JOIN `egl_achievement` `b`
ON `a`.`achievement_id` = `b`.`id`
WHERE `a`.`achievement_id` IS NULL
And then with the user
SELECT * FROM `egl_achievement_member` `a`
RIGHT JOIN `egl_achievement` `b`
ON `a`.`member_id` = 57
AND `a`.`achievement_id` = `b`.`id`
WHERE `a`.`achievement_id` IS NULL
Here is a pretty sweet schedule

Many to many relationship queries

I'm a bit confused about many to many relationship tables, and the code that goes with them.
I have table1:
id, username
And table2:
id, votes_up, votes_down
And a helper table (htable):
vu, vd, adsid
What I want to happen is, when an ad is voted up or down, this vote doesn't go to all adverts.
My attempt at selecting data:
mysql_query("SELECT *
FROM dbo.tab2
INNER JOIN dbo.htable
WHERE tab2.votes_up = htable.vu
AND htable.votes_down = htable.vd
INNER JOIN dbo.tab1
WHERE htable.adsID = table1.ID");
And my insert attempt:
mysql_query("INSERT INTO dbo.htable (vu, vd, adsid)
VALUES
(SELECT FROM dbo.tab2.votes_up, dbo.tab2.votes_down , dbo.tab1.id)");
My question: Are these two queries correct? If not, how can I fix them? and what is the update query ?
I do not really understand your question, but your SQL queries are wrong. They should probably be something like:
SELECT
*
FROM
dbo.tab2 as tab2
INNER JOIN dbo.htable as htable
ON tab2.votes_up = htable.vu
AND tab2.votes_down = htable.vd
INNER JOIN dbo.tab1 as tab1
ON htable.adsID = tab1.ID
and
INSERT INTO dbo.htable (vu, vd, adsID)
SELECT
votes_up, votes_down, ID
FROM
dbo.tab2

Categories