MySQL Query to join tables based on columns - php

Just looking for some help with this, i'm sure it is incredibly simple but after so many hours doing other areas of my site, i'm going a bit batty.
I just have a gaming competition whereby I have a table called 'leaders' that has only these columns:
fk_memberid | points_total
Quite simple. Then I have this query I found elsewhere on this forum to just get the rankings of each member.
SELECT
fk_memberid,
points_total,
(SELECT COUNT(*)+1 FROM leaders WHERE points_total>x.points_total) AS rank_upper,
(SELECT COUNT(*) FROM leaders WHERE points_total>=x.points_total) AS rank_lower
FROM
`leaders` x
My question is, how do I link the fk_memberid column to another table called "members" to the corresponding column "k_memberid"? I do this all the time of course but for some reason i'm struggling in this case due to the different type of query i'm familiar with above.
Sorry for the likely incredibly easy answer. Appreciate the help.

A quick example here:
SELECT l.fk_memberid, l.points_total, m.first_name FROM leaders l
left join member m
on m.k_member_id=l.fk_member_id
WHERE ...
This will give you back a table with 3 columns, 2 from leader table and "first_name" (assuming it exists) from member table

Do one thing
SELECT * FROM Table1 T1, Table2 T2
WHERE T1.column_name = T2.column_name AND Another_comditio(if you want);
may be it will help you

SELECT *
FROM leaders
LEFT JOIN members ON members.k_memberid = leaders.fk_memberid

Related

How do I combine tables with SQL?

Ok, I have two tables of information: movies & history. My movies db has all the information about the movies. These are the rows in movies: id, title, photo, destination, description, rating, length, likes.
My history db has all the information about what movies the user has clicked on. These are the rows in history: id, user_id, movie_id.
The Question
I'm working on a feature called "My History." How do I show their history but also get the information from the movies in one SQL query?
For example:
$db->query("SELECT * FROM movies ORDER BY TABLE history WHERE user_id='$id'");
I apologize if the answer seems simple. This is my first year working with programming in general. Thanks for any help give.
Your query would be:
SELECT * FROM movies m
INNER JOIN history h ON h.movie_id = m.id
WHERE h.user_id = $id
ORDER BY h.id --not sure what you want to order by, but it goes here
That being said, you need to be aware of SQL Injection. You should be using prepared statements instead of just adding variables directly into your query.
You have some error in your query SQL.
I think you can try: (in Mysql)
SELECT movies.* FROM history INNER JOIN movies ON history.movie_id = movies.id WHERE user_id = $id
What you are looking for is a JOIN in MySQL. You'll want to do something similar to this:
SELECT * FROM movies m
JOIN history h ON m.id=h.movie_id
AND h.user_id = $id
ORDER BY <column name>;
Basic concept behind this JOIN is you are taking the primary key from movies (id) and joining on its corresponding foreign key on history (movie_id).
It's also worth noting that JOIN, CROSS JOIN, and INNER JOIN are all syntactic equivalents in MySQL.
Since you are just starting your first year in programming, I would highly recommend looking in to the documentation on JOIN and fully understanding it yourself, rather than copying and pasting an answer that works here. It will be beneficial to you in the long run! See the MySQL documentation on JOIN syntax here.

Multiple table select grouped query

We need to grab the last and newest 20 entries from different tables. However, the GROUP BY statement skips records because we are working with LEFT JOIN on tables.
All these records are linked to unique persons in another table. We store these person's id's in an array for more queries later.
We have a few tables (in which all those person id's are stored) and we want to get them sorted and grouped.
The tables are like this:
SELECT lastRecord+personID FROM t1
SELECT lastRecord+personID FROM t2
SELECT lastRecord+personID FROM t3
SELECT lastRecord+personID FROM t4
WHERE t5.Essential_Column_Name = '1'
GROUP BY personID
ORDER BY 'all the latest entries'
LIMIT 20
With that, the relevance of all the latest entries should be equal.
We do have a timestamp column as well. Perhaps that might work better.
Any input is highly appreciated!
For people looking for an answer on this; this is the right post, answer and update to this Q:
UNION mysql gives weird numbered results
With thanks to all for the ideas and providing the paths to the right solution.

Select query from mysql database

Hello I am having a hard time trying to SELECT all of the information I need from two tables, the following two tables are:
Person: |id|fname|mname|lname| and Related: |id1|id2|relationship|
and I want the following to be displayed back from the SELECT query:
|id1|fname(of id1)|id2|fname(of id2)|relationship|
SO the Related table has two id's that are FOREIGN KEYS to Person(id), and I need to
SELECT id1, (id1's first name), id2, (id2's firstname), and the relationship.
I've tried something like this and a few other SELECT queries but I can't seem to get it to work:
SELECT p.fname, r.id1, r.id2, r.relationship
FROM Person p, Related r
INNER JOIN Related ON first.id = r.id1
INNER JOIN Related ON second.id = r.id2;
Any help will be greatly appreciated! Thank you!
You're joining on Related thrice. You only need to join once, and you need to join on Person again.
SELECT id1, p1.fname, id2, p2.fname, relationship
FROM Person p1
JOIN Related ON (p1.id = id1)
JOIN Person p2 ON (id2 = p2.id)
I've found a website for you (w3schools) and it should have all the information you need for the SELECT function you're trying to get. Hope this helps:
http://www.w3schools.com/php/php_mysql_select.asp

Mysql join query retrieving profile images of users with ids from other table

I'm having trouble with a join query, my issue is as follows.
Table: battles
Fields: id,attacker_id,defender_id
Table: users
Fields: id,profile_image
I would like to do a query to retrieve a battle and get the profile images as well from the other table.
Is there a way to do this in a single or do I have to do more than one?
Thanks in advance.
I wanted to wait a while to see if you had any attempt or if you will answer my first question to know if I understood the problem. But maybe you don't have a starting point. Try something like:
SELECT
a.profile_image as attacker_profile_image,
d.profile_image as defender_profile_image
FROM
`battles` b
LEFT JOIN
`users` a
ON
b.`attacker_id` = a.`id`
LEFT JOIN
`users` d
ON
b.`defender_id` = d.`id`
the problem here is the fact that you need to join with the users table twice, so you will need to create aliases for the columns you plan to use
This query will fetch the two images only, you will need to add the extra fields

What type of mysql query do you run to compare two fields in separate tables?

I have a mysql table(table1) which has the following row:
topic_id: 1
topics: programming
description: A programming language is an artificial language designed to...
I have another table(table2) with this row:
desc_id: 1
description: In mathematics and computer science, an algorithm is an effective...
topics: mathematics, computer science, programming
What I'm looking to do is to run a query to compare the two topics fields and let me know which topics exist in table2 that don't exist in table1.
For instance, comparing the two above I'd like to run a query to let me know that topics mathematics and computer science don't exist in table1.
I would use a subquery, but it can also be done with innerjoins :
SELECT *
FROM `table2`
WHERE `topics` NOT IN (
SELECT DISTINCT(topics)
FROM `table1`
)
you can try NOT IN
i.e.
SELECT topics FROM table2 where topics NOT IN( select topics from table1)
If you normalized your table2 so that the topics list is in a separate sub-table, this would be a trivial query. As it stands now, it's difficult as by default mysql won't see those seperate topics in table2.topics as discrete topics. It's just a long string that happens to have commas in there.
Thankfully, MySQL has the find_in_set() function, which can help out immensely, but this function isn't available elsewhere. Not having access to your dataset, I'm just guessing here, but this should do the trick:
SELECT table1.topics, count(table1.topic_id) AS cnt
FROM table1
LEFT JOIN table2.topics ON FIND_IN_SET(table1.topics, table2.topics) = 0
GROUP BY table1.topics
HAVING cnt = 0
Basically, join the tables wherever the table1 topic is NOT in a table2 topic and count how many times the table1 topic shows up like this. If it shows up zero times, then it's present in at least one record in table2.
normalize by creating a third table, one that links table 2 to table 1 with a many to many relationship.
Table_1
id, etc
Table_2
id, etc
Table_3
id, table1_id, table2_id
you could then use simple joins to create a query that will pull the relavent data
SELECT * FROM Table_1 LEFT JOIN Table_3 ON Table_1.id = Table_3.table1_id WHERE Table_3.table2_id = $table2_id
This will pull all topics for the course.

Categories