I have 2 tables.
Table 1 : t_atc_list
id | a_name | s_title | r_name
------------------------------
80 | ss | 128 | 5
Where s_title & r_name is foreign key.
Table 2 : t_s_list
s_id | title
-------------
128 | Song Title
I want have used left join query on this..to select all values of 't_atc_list' if it mightbe in 't_s_list'..
$query=mysql_query("SELECT t.s_title, s.title from t_atc_list t LEFT OUTER JOIN t_s_list s ON t.s_title=s.s_id");
$row=mysql_fetch_array($query);
While if I use right join its working..
$query=mysql_query("SELECT t.s_title, s.title from t_s_list s RIGHT OUTER JOIN t_atc_list t ON t.s_title=s.s_id");
$row=mysql_fetch_array($query);
Whats the reason left join is not working but right join is going well? And I think both the queries are identical than whats the problem?
This is a strictly data related issue you have there, your SQL syntax is correct, but your data must not line up.
For a visualization of SQL, look here: http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html
Also if you do a right join, that means you are simply getting data from the 2nd table, and nulls in the first. I am just guessing here as I see no real data examples.
Related
I want to work on SQL. inner join is not working missing. I am using two tables get data on "city_id " field these table code so please help me
inventory
==========================================
inventory_id | city_id | title |is_enabled
==========================================
1 | 1 | abc | 1
2 | 1 | bcd | 1
cities
====================================
city_id | city | title
===================================
1 | delhi | abc
2 | nodia | bcd
SELECT * FROM inventory i
INNER JOIN cities c
ON i.city_id = c.city_id
WHERE i.is_enabled = 1
ORDER BY i.inventory_id DESC LIMIT 10;
Some databases (such as MS Access and MySQL) do not support FULL OUTER JOIN.
However, FULL OUTER JOIN is rarely needed -- and almost never when you are using keys defined between tables. Well structured databases have keys with appropriate values.
I suspect an INNER JOIN does what you want:
SELECT . . . -- list out the columns you want
FROM inventory i INNER JOIN
cities c
ON i.city_id = c.city_id
WHERE i.is_enabled = 1
ORDER BY i.inventory_id DESC
LIMIT 10;
This query assumes that the inventory rows have a valid city_id. If some are NULL (an allowed, non-matching value), you can use LEFT JOIN instead.
Some other notes:
List out the columns you want explicitly. In particular, duplicate column names can be problematic.
Use table aliases, so the query is easier to write and to read.
Qualify all column names. I'm guessing that is_enabled comes from inventory. I should not have to guess.
Do not put single quotes around numeric constants. I am guessing that is_enabled is a number, not a string.
Im having some issues getting the result I want from two tables
table #1: history
customer_id | Action
------------------------
217 | buy
------------------------
218 | sell
------------------------
219 | hold
------------------------
table #2: Customers
customer_id | name
----------------------------
217 | Alan
----------------------------
218 | Jan
----------------------------
219 | Rick
I have a really long query now, but essentially I want to add to match the name with the amount. I tried this but it didn't work:
(SELECT action AS action FROM "history` LEFT JOIN ON " customer(customer_id=customer_id)`)
I'm not really familiar with doing queries so any help would be appreciated
It should be this:
SELECT h.Action AS action
FROM history h
LEFT JOIN Customers c
ON h.customer_id = c.customer_id
You either need to specify the tables or create an alias with which to associate columns/data.
Is a simple join
select action
from history
left join Customers on Customers.Customer_id = history.customer_id
and you can confirm using
select history.customer_id, Customers.Customer_id history.action , Customers.name
from history
left join Customers on Customers.Customer_id = history.customer_id
You can JOIN tables like this:
SELECT history.action AS Action ,Customers.name AS Name
FROM `history`
LEFT JOIN `Customers` ON history.customer_id = Customers.customer_id;
I am trying to generate result from a SQL, but i am not getting desired results.
above image is the result of following query
SELECT DISTINCT
U.USERID, U.shopName, U.image, P.PID
FROM users U, products P
WHERE P.USERID=U.USERID
GROUP BY U.USERID
ORDER BY P.PID DESC
Now what i want to do is that there is another record for USERID 2 and 3 with PID 3 and 5 respectively, let me show you the image
I want to retrieve latest record entered in the table but with distinct USERID
e-g i want to retrive this
userid | shopname | image | PID
3 | shop name | image | 5
4 | shop name | image | 4
2 | shop name | image | 3
any help will be appreciable.
select * from "table" grou by ID and order by Desc
Use it like below, Do group by with PID.
SELECT DISTINCT U.USERID, U.shopName, U.image, P.PID FROM users U, products P WHERE P.USERID=U.USERID GROUP BY P.PID ORDER BY P.PID DESC
I am not sure if I understood your problem, but perhaps the following query solves your problem:
SELECT U.USERID, U.shopName, U.image, P.PID
FROM users U, products P
WHERE P.USERID=U.USERID
AND P.PID in (select min(p2.pid) from products p2 where u.userid = p2.userid)
A word of warning: it might be more efficient to use the ORDER BY trick and filter the results externally.
I have three tables in a mySQL database that I am querying with PHP:
players
player_id | player_name
-----------------------
1 Tom
2 Dick
3 Harry
games
game_id | game_name
-------------------
1 Tennis
2 Cricket
3 Rugby
gamePlayerRel
game_id | player_id
-------------------
1 2
1 3
2 3
3 2
3 3
I want a query that will return the players id and name as well as the games that they play. If they play no games - as in the case of Tom (1) - then I want the id and name and a null or 0 value.
Desired Result
player_id | player_name | game_id | game_name
---------------------------------------------
1 Tom null null
2 Dick 1 Tennis
2 Dick 3 Rugby
3 Harry 1 Tennis
3 Harry 2 Cricket
3 Harry 3 Rugby
The closest I can get is with the following query:
SELECT players.player_id, players.player_name, gamePlayerRel.game_id, games.game_name
FROM players
INNER JOIN gamePlayerRel
INNER JOIN games
ON players.player_id = gamePlayerRel.player_id
AND gamePlayerRel.game_id=games.game_id
This gets close except that it does not return data for players with games assigned to them. In the above examples the result is as I want except that Tom (1) with his null values is left out.
I'm a super noob at this so if I'm coming at it from the wrong angle please say so and if you can suggest a query that will do what I'm after you would make my day.
Thanks in advance for any help and advice.
To return the result set as you've shown you need to actually do two outer joins
SELECT players.player_id, players.player_name, gamePlayerRel.game_id, games.game_name
FROM players
LEFT OUTER JOIN gamePlayerRel ON players.player_id = gamePlayerRel.player_id
LEFT OUTER JOIN games ON gamePlayerRel.game_id=games.game_id
In your case this should work just fine, however, what I really think you're trying to do is an inner join between games and gamePlayerRel and then a Left Outer Join between that virtual table and the players table. You can accomplish that via something like this:
SELECT players.player_id, players.player_name, playerGames.game_id, playerGames.game_name
FROM players
LEFT OUTER JOIN (Select gameplayerRel.player_id, games.game_id, games.game_name from games inner join gamePlayerRel on games.game_id = gamePlayerRel.game_id) playerGames
on players.player_id = playerGames.player_id
In your case you'd never need this alternative syntax, but there are some times when things can get messed up because the two left outer joins way is not exactly logically equivalent.
Here is a SQL Fiddle showing the results of the queries
I know you're using mysql, but this article does a good job of explaining the nuances of the joins, but it is written for MSSQL, although it should apply to you just the same. http://weblogs.sqlteam.com/jeffs/archive/2007/10/11/mixing-inner-outer-joins-sql.aspx
This should do the trick
SELECT players.player_id, players.player_name, gamePlayerRel.game_id, games.game_name
FROM players
INNER JOIN gamePlayerRel ON players.player_id = gamePlayerRel.player_id
LEFT OUTER JOIN games ON gamePlayerRel.game_id=games.game_id
You need to join each table individually and also need to use a LEFT OUTER JOIN for your games table. This will pull in at least one record for every match in the players/gamePlayerRel tables. If there isn't a match you'll be returned a NULL value.
After being nudged in the right direction by the helpful folk of SO I have got a query that does what I am after though I am still not 100% sure why it works.
SELECT players.player_id, players.player_name, gamePlayerRel.game_id, games.game_name
FROM players
INNER JOIN gamePlayerRel ON players.player_id = gamePlayerRel.player_id
LEFT OUTER JOIN games ON gamePlayerRel.game_id=games.game_id
Thanks to those who commented. Once again this site proves one of the most useful I have ever found :)
I have a table in my MySQL database that, in part, looks like this:
+----+-------+-------+
| id | owner | onwed |
+----+-------+-------+
| 1 | A | B |
| 2 | B | A |
| 3 | C | D |
| 4 | D | C |
| 5 | E | X |
+----+-------+-------+
They important feature here is that all the entries are paired, so that each "owner" is also "owned" by the record they correlate to. A "owns" B, and also B "owns" A. D "owns" C, and also C "owns" D.
However, in row 5,we have a problem. E "owns" X, but there is no entry for X "owning" E.
I need to be able to go through this table, which has thousands of records, and find all instances like row 5, where we have an orphaned record. Where there is no corralating with the "owner" and "owned" fields having a matched opposite. Also, there is no assurance that paired rows will follow each other as they do in my example.
This problem goes way beyond my MySQL abilities. I know how to do a search when I know what the value I'm looking for is. But I don't know how to go through each row one by one, take values out, and then use those values to do another search. I hope someone can help me out and I apologize that I'm so clueless on this matter that I don't have any code to suggest.
I'm not so worried about efficiency, in that this is a check I would only run every now and again when there is reason to suspect a problem. Also, if it helps, I manage my MySQL database from a PHP script, so if there is PHP code that can be leveraged to make the task more manageable, that could also be utilized.
What you need is a join. If you join the table on itself with the owned on owner.
SELECT T1.Id, T1.Owner, T1.Owned, T2.Id, T2.Owner, T2.Owned
FROM tablename T1
LEFT JOIN tablename T2
ON T1.Owned = T2.Owner
WHERE T2.Owned != T1.Owner
OR T2.Id IS NULL
Try to run the query without the WHERE clause to see what this join does. You get both owners and owned on a single row and then you can compare if they match.
You could try a query similar to (not sure about the backquotes of MySQL)
SELECT * FROM `table`
WHERE (`owner`,`owned`)
NOT IN (SELECT `owned`,`owner` FROM `table`);
There are probably cleaner solutions without selfjoins
There are better ways, but this will work:
SELECT
*
FROM
table
WHERE
id NOT IN (
SELECT
id
FROM
table s1
WHERE
s1.owner = (
SELECT
onwed
FROM
table s2
WHERE
s2.onwed = s1.owner
)
);
Its easy:
select t1.id from tableName as t1 left join tableName as t2
on t1.owner = t2.owned and t1.owned = t2.owner
where t2.id is null
select
*
from
mytable
where id not in (
select
m1.id
from
mytable m1,
mytable m2
where
m1.owner=m2.owned
)
You can try this- demo below :
http://sqlfiddle.com/#!2/0db47/7
SELECT a.id, a.owner, a.onwed
FROM TableName a
LEFT JOIN TableName b
ON (a.Owner = b.Owner AND a.Onwed = b.OnWed) OR
(a.Owner = b.OnWed AND a.Onwed = b.Owner)
GROUP BY a.id, a.owner, a.onwed
HAVING COUNT(*) = 1
SQLFiddle Demo