PHP combine two tables and list all from first table - php

I want to combine two tables.
table A: has multiple posts with unique URL and table B has votes for specific posts from table A.
Now I want to list all rows from table A and if a post has a vote in table B to attach that to one row.
I've tried this, but it excludes the posts who matches the table A with table B. It returns only without any votes.
SELECT a.id,a.url,a.content,a.sourcetype,a.width,a.height,a.totalvotes,a.score, b.postid,b.userid,b.votetype
FROM create_general a
LEFT JOIN votes b ON a.url=b.postid
WHERE a.status='1' and a.score > 0 order by a.url desc
LIMIT 24

Perhaps it would be nice to know more about the table structure, but you definitely do something wired in your on clause:
ON a.url=b.postid
This says, that the "url" in "table a" has to be the same than the "postid" in "table b".
Usually a url would look like this: "https://google.de" and a postid is just a number, perhaps "7", so they cannot be the same.

Related

How to compare two rows from different tables and show the table values if the rows match?

I have two different tables. One is person and the other one is Cardholder. Both of these tables have one row with the similar name and same value and its called personId. What I am trying to do is compare the row personId on the person table to personId on the Cardholder table and print only rows that match the value of personId on both tables. How would I write in PHP to do such task? I tried few things but failed to do what I intend.
The sql query would look something like this :
SELECT P.* FROM person P
INNER JOIN Cardholder C ON C.personId=P.personId
this would only select the fields from the table person that has a match on personId in the Cardholder table.
You will need code like this one
MySQL Code: -
("SELECT Cardholder.personId, person.personId FROM Cardholder INNER JOIN person ON Cardholder.personId = person.personId");
PHP Code: -
if (count($SQLstatment) > 0) {Exist} else {Not}

Searching multiple tables in MySQL database

I have several different tables in my database(mySQL).
Here are the relevant coumns for the tables
table_tournaments
tournamentId
tournamnetName
tournamentStatus
table_tournament_results
tournamentId
playerId
playerName
playerRank
tournamnetParticipants
table_players
playerId
playerName
The tournaments table contains the information about the tournament, the tournament results table shows the results from that table
I want to search the tournaments table by name and then with the returned results get the information from the tournament results table.
SELECT * FROM `tournaments` `WHERE` `tournamentName` LIKE "%Query%"
I'm not sure how to go about this, maybe I need to do something via PHP, any and all help is appreciated.
You can get the results you want with a join operation.
This is an example of an outer join, returning all rows from t that have the string 'foo' appearing as part of tournament_name, along with any matching rows from r.
A relationship between rows in the two tables is established by storing a common value in the tournamentId column of the two tables. The predicate in the ON clause specifies the condition that determines if a row "matches".
SELECT t.tournamentId
, t.tournamentName
, t.tournamentStatus
, r.playerId
, r.playerName
, r.playerRank
FROM table_tournaments t
LEFT
JOIN table_tournament_results r
ON r.tournamentId = t.tournamentId
WHERE t.tournament_name LIKE '%foo%'
ORDER
BY t.tournamentId
, r.playerId
The t and r that appear after the table names are table aliases, we can qualify references to the columns in each table by prefacing the column name with the table alias and a dot. This makes the column reference unambiguous. (In the case of tournamentId, MySQL doesn't know if you are referring to the column in t or r, so we qualify it to make it explicit. We follow this same pattern for all column references. Then, someone reading the statement doesn't need to wonder which table contains the column playerId.
Your Query may be like this
SELECT a.*, b.tournamnetName FROM table_tournament_results a
left join table_tournaments on a.tournamentId=b.tournamentId
WHERE b.tournamnetName LIKE "%Query%"

Retrieving data from multiple tables and listing them in a list

I'm having some problems retrieving data from two tables and then listing them. I'd like to list the user's feed posts and their likes activity all in one.
Feeds - Table for users posts
Likes - Table for users likes (So when a use likes a post, a record is added to likes (Table likes contains data which contains the feeds ID of the post liked)
What I'm attempting to make: List BOTH feeds and user's Like activity in an ACTIVITY WALL.
So it should output like (ordered by timestamp desc):
"THIS IS A POST by user A"
Shows that user C liked user B's post
"THIS IS A POST by user B"
"THIS IS A POST by user L"
Shows that user A liked user F's post
"THIS IS A POST by user F"
-and it goes on-
My current SQL:
SELECT * FROM feeds,likes WHERE feeds.deleted!=0 or likes.deleted!=0 ORDER BY feeds.timestamp, likes.timestamp
However, my problem is I have no idea how to link both tables, since the IDs in my 'feeds' differ from those in 'likes'
To combine the two sets, you can use a UNION ALL set operator.
Something like this:
SELECT f.timestamp AS `timestamp`
, 'feed' AS `src`
, f.feed_id AS `id`
, f.feed_content AS `content`
FROM feeds f
WHERE f.deleted!=0
UNION ALL
SELECT l.timestamp AS `timestamp`
, 'like' AS `src`
, l.like_id AS `id`
, l.note AS `content`
FROM likes l
WHERE l.deleted!=0
ORDER BY 1 DESC
Note the the queries (on either side of the UNION ALL operator) need to match, in terms of the number of columns returned, and the datatype of each column.
To accommodate differences, such as extra columns returned from one table, but not from the other, you can add literal expressions in place of the "missing" columns.
The return of the extra src column is one way we can use to distinguish which query a row was returned by. It's not mandatory to return such a column, but it's something I often find useful. (The src column could be removed from each query, if it's not useful for your use case.)
Note that it's also possible to combine the results from more than two queries in this way, we'd just add another UNION ALL and another query.
The column names in the combined resultset are determined from the first query. The column names and aliases in the second query are ignored.
The ORDER BY applies to the entire set, and follows the last select.
Query should be linked via postID
F=feeds table, L=likes table, U1=usertable linked to owned feeds, U2=usertable linked to likes table
SELECT F.postTitle+' posted by '+ U1.username,'liked by'+U2.username
FROM likes L
LEFT JOIN feeds F on (F.postID=L.postID)
LEFT JOIN users U1 on (U1.userID=F.userID)
LEFT JOIN users U2 on (U2.userID=L.userID)
ORDER BY L.date,L.postID DESC
When you write SELECT * FROM feeds,likes... you are implicitly CROSS JOINing both tables. The engine will combine every record in each table with every record in the other. That is far from what you want.
I don't think you should be "linking" both tables, either. What you need, roughly speaking, is to get every post and every like, and then order that big set according to timestamps.
It sounds more like a UNION between two queries, and an ORDER BY applied to the whole UNION. UNIONs are never easy on the eye, by the way...
The thing with UNIONs is that both sub-queries need to return the same amount of columns. Not knowing exactly which columns you have, I'll show you one possible solution:
SELECT activity, timestamp FROM (
( SELECT CONCAT(u.name,' posted ',f.content) as activity, timestamp
FROM user u
JOIN feed f on (f.user_id=u.id)
WHERE f.deleted!=0
) UNION
( SELECT CONCAT(u.name, ' liked a post by ',u2.name) as activity, timestamp
FROM user u
JOIN likes l on (l.user_id=u.id)
JOIN feed f on (l.feed_id=f.id)
JOIN user u2 on (f.user_id=u2.id)
WHERE l.deleted!=0
)
) as whole_result
ORDER by timestamp desc
You should, of course, modify this to match your structure.
Hope this helps!
I think, it's better to use 3rd table, say, "actions", and insert to it real actions. Then just select rows from this table, joined to "posts" & "users" table.
When user posts articles, o likes an article, insert corresponding row to "actions" table.
actions table:
|id|action_name|user_id|post_id| date |
1 posted 3 3 5/7/2014
2 liked 5 3 5/7/2014
3 liked 4 3 6/7/2014
4 posted 5 6 7/7/2014
5 liked 3 6 7/7/2014
SELECT user_name a, post_title b, action_name c FROM actions c LEFT JOIN users a ON a.id=c.user_id LEFT JOIN posts b ON b.id = c.post_id ORDER BY c.date DESC LIMIT 10
Then, in loop, choose how to display this data, according to "action_name".
In such way you can expand your wall for other activities, +use indexes for better database performance.

Select from one table where id (from another table) exists

First of all, I'd just want to say that I'm sorry for the poor title. I'm really struggling with explaining the problem I'm facing in just a short sentence.
I have a table called actors which contains an aID (primary key) and an aName and some more stuff. I also have a table called videos which contains vID (primary key) and other data. The third and last table I have is called connections and that one contains a primary key, a cVideoID and a cActorID.
Let's say I have created a video and when I navigate to the video *www.example.com/video.php?v=primary_key* I'd like to print out all actors who are in that movie (actor1, actor2, actor3 and actor4). Therefor I created the connections-table to keep track of all movie-actor connections. For every movie I create I connect the actors with the movie.
I thought that I could do something like this:
<?php
$result2 = mysql_query("SELECT `actors`.`aID`, `actors`.`aName` FROM `actors` WHERE `connections`.`cVideoID` = {$_get['v']}");
while($actors = mysql_fetch_array($result2))
{
echo "<a href='actor.php?id={$actors['aID']}>{$actors['aName']}</a> ';
}
?>
But it seems like that's not working. Any ideas?
What you want to do, is select all of the entries from connections, where the video ID is the selected video. Then, you JOIN on the actors table, to get all of the information about the actors that were found.
Example: Get all of the actor's names for a specific video ID:
SELECT a.aName
FROM connections c
LEFT JOIN actors a
ON a.aID = c.aID
WHERE c.vID = 1;
SQL Fiddle
What you need here is a join.
A normal left join works like this:
LEFT JOIN [name of table] [name of table you will want to use]
ON ([where statements searching for the right columns to join])
So your query will look something like this:
SELECT a.aID, a.aName
FROM `connections` c
LEFT JOIN `author` a ON (c.cActorID=a.aID)
WHERE c.cVideoID=[id of the video]
Now first of all you say the database you want to catch the columns aID and aName from the table a next you use the FROM statement to "import" the connections table as "c". You then load the author table and make it accessible as "a" (see the select statement a.[...]) and you also say that it should join the two tables ON every c.cActorID=a.aID and in the end you make a where statement to declare you are only searching for videos with the c.cVideoId=[id]

how to get a count of records from Table B to place next to the name of each row in Table A

I have so many problems trying to understand this, so forgive me for what's most likely a repeat question.
I have 2 tables, one called "category" and one called "items". Each row in "items" has a category_id field that matches the category_id field in the "category" table.
In one mysql statement, I want to get a row count for each category_id in "items", but also retrieve the category_name in "category", so I can print out a list of categories like this:
Foo (3)
Bar (1)
Duh (6)
The questions I've found here so far only seem to return the category_id's from "items", so the result would look like this:
1 (3)
2 (1)
3 (6)
Follow? I'm sure it can be done in one mysql statement, so far I've had to resort to two separate queries for the sole purpose of getting that little number.
This should work for you;
SELECT c.name AS theName, COUNT(i.id) AS theCount
FROM category AS c JOIN items AS i ON i.category_id = c.id
GROUP BY i.category_id
//Edit
Sorry I should then explain this.
Select Is grabbing the category name and the count of the items.
From Is doing a join that will bind items and categories together.
Group By Is ensuring that the Category ID is the unique thing in the query.

Categories