configuring how to pull data out of 3 tables with mysql - mysql

Here is how the the database is layout. I can connect to DB fine.
I had it pullling from database two things but adding a third i can not get it to pull. I just need some help if i could ..
database - mmoore_drupal
table 1
table name = content_type_uprofile
data
vid= 19723
nid =19674
field_name_value = matthew moore
table 2
table name = location_instance
data
lid = 1521
vid = 19723
nid = 19674
table 3
table name = location
data
lid = 1521
street =
city =
country =
latitude =
longitude =
I am trying to pull name and then other info from the other two tables. But mainly i need to have name and other information from location. I thought i had to have the other table to associate the connection. Any help is appreciated.
$query = "SELECT content_type_uprofile.field_name_value,location.street,location.city
FROM location_instance,location,content_type_uprofile
WHERE location_instance.lid = location.lid and location_instance.nid=content_type_uprofile.nid"
$result = mysql_query($query) or die(mysql_error());
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
echo $row['nid']."-".$row['street']. " - ". $row['city'];
echo "<br />";
}
?>

Use this SQL (explicit join syntax):
SELECT
content_type_uprofile.nid,
location.street,
location.city
FROM
content_type_uprofile
INNER JOIN location_instance
ON (content_type_uprofile.nid = location_instance.nid)
INNER JOIN location
ON (location_instance.lid = location.lid)
The SQL that you posted is using implicit join SQL syntax.
I think for some reason, I think the line in your SQL:
WHERE location_instance.lid = location.lid and location_instance.nid=content_type_uprofile.nid
is filtering out all the rows from your result set. I'm not sure because I avoid the implicit syntax.
You were also missing the nid field which your PHP code is looking for in the result set.
As long as your data is correct (i.e. the fields that you are joining on have the right values), the SQL that I posted will work for you.

You ever done something with join's?
select *.locaition,
*.content_type_uprofile
from location_instance li
inner join location l on l.lid = li.lid
inner join content_type_uprofile ctu on ctu.vid = li.vid

Related

Chain of SQL subqueries within large query of JOINS

I am trying to structure a SQL query with complex nested select operation!
My original SQL query successfully JOINS around 30 tables, the data are retrieved as wanted! However every fetched record in the 30 tables
has many records in another table called (Comments)! What I want to do is to atribute every record in the (Comments table) to its record in the other
30 tables by IDs and retrieve them all together in one query. Yet this is not the only challenge, some of the 30 tables have in addition to the records in
(Comments table) more records in another table called (extras), so i am looking for additional subquery within the main subquery within
a LEFT JOIN inside the outter main query.
To make the idea more clear; without subquery the script will be as following:
$query = $mysqli->query("
SELECT
parent1.parent1_id,
parent1.child1_id,
parent1.child2_id,
parent1.child3_id,
parent2.parent2_id,
parent2.child1_id,
parent2.child2_id,
parent2.child3_id,
child1.child1_id,
child1.child1_content,
child2.child2_id,
child2.child2_content,
child3.child3_id,
child3.child3_content
FROM
parent1
LEFT JOIN child1
ON child1.child1_id = parent1.child1_id
LEFT JOIN child2
ON child2.child2_id = parent1.child2_id
LEFT JOIN child3
ON child3.child3_id = parent1.child3_id
LEFT JOIN followers
ON parent1.user_id = followers.followed_id
AND parent1.parent1_timestamp > followers.followed_timestamp
AND parent1.parent1_id NOT IN (SELECT removed.isub_rmv FROM removed)
AND parent1.parent1_hide = false
WHERE
followers.follower_id = {$_SESSION['info']}
{$portname_clause}
ORDER BY
parent1.parent1_timestamp DESC
LIMIT
{$postnumbers}
OFFSET
{$offset}
")
// Now fetching and looping through the retrieved data
while($row = $query->fetch_assoc()){
echo $row['child1_content'];
$subquery1 = $mysqli->query("SELECT extras.child1_id,
extras.extrasContent FROM extras WHERE extras.child1_id =
{$row['child1_id']}");
while($row1 = $subquery1->fetch_assoc()){
echo $row1['extrasContent'];
}
echo $row['child2_content'];
$subquery2 = $mysqli->query("SELECT extras.child2_id,
extras.extrasContent FROM extras WHERE extras.child2_id =
{$row['child2_id']}");
while($row2 = $subquery2->fetch_assoc()){
echo $row2['extrasContent'];
}
echo $row['child3_content'];
$subquery3 = $mysqli->query("SELECT extras.child3_id,
extras.extrasContent FROM extras WHERE extras.child3_id =
{$row['child3_id']}");
while($row3 = $subquery3->fetch_assoc()){
echo $row3['extrasContent'];
// Here i need to run additional query inside the subquery 3 to retrieve the (Comments table) data beside (extras table)
$subquery4 = $mysqli->query("SELECT comments.comment_id, comments.comment FROM comments WHERE comments.child3_id = {$row['child3_id']} OR comments.child3_id = {$row3['child3_id']}");
while($row4 = $subquery4->fetch_assoc()){
echo $row4['comment'];
}
}
} // No sane person would make such code
Because the code above would be totally rediclious i searched for a better way to carry it out, and thats where i came across the subquery
concept, but i do not know anything about subqueries, and shortly after i studied it i came up with this messy code, check it below!
I am not posting the origianl code here because it is too long, i am including a virtual example of the tables i want to apply the
query on in order to demonstrate the process.
SELECT
parent1.parent1_id,
parent1.child1_id,
parent1.child2_id,
parent1.child3_id,
parent2.parent2_id,
parent2.child1_id,
parent2.child2_id,
parent2.child3_id
FROM
parent1
LEFT JOIN
( SELECT
child1.child1_id,
child1.child1_content
FROM
child1
WHERE
child1.child1_id = parent1.child1_id ) child1
( SELECT extras.extrasID, extras.extrasContent
FROM
extras
WHERE
extras.child1_id = child1.child1_id )
ON parent1.child1_id = child1.child1_id
LEFT JOIN child2
( SELECT
child2.child2_id,
child2.child2_content
FROM
child2
WHERE
child2.child2_id = parent1.child2_id )
( SELECT
extras.extrasID,
extras.extrasContent
FROM
extras
WHERE
extras.child2_id = child2.child2_id )
ON parent1.child2_id = child2.child2_id
LEFT JOIN child3
( SELECT
child3.child3_id,
child3.child3_content
FROM
child3
WHERE
child3.child3_id = parent1.child3_id )
( SELECT
extras.extrasID,
extras.extrasContent
FROM
( SELECT
comments.comment_id,
comments.comment
FROM
comments
WHERE
comments.child3_id = extras.child3_id ) extras
JOIN child3
ON extras.child3_id = child3.child3_id )
ON parent1.child3_id = child3.child3_id
LEFT JOIN followers
ON parent1.user_id = followers.followed_id
AND parent1.parent1_timestamp > followers.follower_timestamp
AND parent1.parent1_id NOT IN (SELECT removed.isub_rmv FROM removed)
AND parent1.parent1_hide = false
WHERE
followers.follower_id = {$_SESSION['info']}
{$portname_clause}
ORDER BY
parent1.parent1_timestamp DESC
LIMIT
{$postnumbers}
OFFSET
{$offset} // <-- Sorry for the bad code formatting!
I am using MySql 5.6.37
I did not get the hang of the subquery concept yet, frankly i got lost and confused as i was studying it and for another reason too mentioned in the note below.
Note: I apologize in advance that i might not be on instant reply because where i live there is no electrecity or ADSL or phones and my
USB modem hardly gets signal, i have only two hours of averege three hours a day of electericity generated by a desil generator. i recharge
my laptop and check internet and the remaining one-two hours are for other life stuff.
I know the joke is on me as i am developing a web project without electricity or permanent internet. BUT LIFE DOES NOT GIVE EVERYTHING! lol.
This is how i solved the problem!
SELECT
parent1.parent1_id,
parent1.child1_id,
child1.child1_id,
child1.child1_content,
comments.comment_id,
comments.comment,
comments.child1_id
FROM parent1 LEFT JOIN
(
SELECT comments.comment_id, comments.comment, comments.child1_id
FROM
(
SELECT comments.comment_id,comments. comment, comments.child1_id
FROM comments
) comments JOIN child1
ON comments.child1_id = child1.child1_id
) comments
ON child1.child1_id = comments.
It needs some aliases and then it's good to go.

DQL And Equivalent SQL Not Returning Same Number Of Result Set

Here is my doctrine query running code:
$queryString = "SELECT ct, count(ct.id), IDENTITY(a.service) "
. "FROM ConnectionTriple ct "
. "JOIN ct.account_connection ac "
. "JOIN Account a WITH (a = ac.account_1 OR a = ac.account_2) "
. "GROUP BY a.service, ct.property, ct.value";
$query = $em->createQuery($queryString);
//echo $query->getSQL();
$results = $query->getResult();
echo count($results);
This above code is returning 2 results(final two from below screenshot) instead of 4(expected). But, when I run the equivalent SQL(got by $query->getSQL()) on phpmyadmin, it returns expected 4 rows which is as below:
Equivalent SQL Query:
SELECT u0_.id AS id0, u0_.value AS value1, u0_.status AS status2, u0_.flag AS flag3, count(u0_.id) AS sclr4, u1_.service_id AS sclr5, u0_.property_id AS property_id6, u0_.account_connection_id AS account_connection_id7 FROM usc_connection_triple u0_ INNER JOIN usc_account_connection u2_ ON u0_.account_connection_id = u2_.id AND (u2_.status = 1) INNER JOIN usc_service_subscriber u1_ ON ((u1_.id = u2_.account_1_id OR u1_.id = u2_.account_2_id)) WHERE (u0_.status = 1) AND (u1_.status = 1) GROUP BY u1_.service_id, u0_.property_id, u0_.value
PHPMyAdmin Result:
So, I guess, there is something wrong in result to object hydration by doctrine, I guess. Anyone has any idea why this might happen/possible solution?
My Doctrine version are:
"doctrine/dbal": "2.3.2",
"doctrine/orm": "2.3.2",
Update: I am certain about the hydration issue. Because, I tried with individual column retrieving and using scalar hydration:
$results = $query->getResult(\Doctrine\ORM\Query::HYDRATE_SCALAR);
This is returning perfectly. Which is expected number of rows, 4 and data as well.
I would say this is totally normal.
As you pointed it out, doctrine (default) hydration mode would represent the result set as an object graph.
An object graph always have a root object (in your case ConnectionTriple ct).
There are 2 ct in your result set (with id 1 and 2).
Doctrine object hydrator will be smart enough to return you and array
of 2 ConnectionTriple objects, each line containing the related data.
The scalar hydrator, howerver will simply return the raw resultset, without building a graph from it.

MySQL join on 2 tables

I need to do a search on 2 simultaneous tables, and I thought that this join would work but its giving me an incorrect syntax error.
$return_arr = array();
$query = mysql_query("SELECT * FROM clients WHERE lastname LIKE '$q%' AND agencyid = '$agencyid'
UNION
SELECT * FROM busclients WHERE busname LIKE '$q%' AND agencyid = '$agencyid'")or die(mysql_error());
if($query) {
while ($result = mysql_fetch_array($query)) {
if(isset($result['busname'])){
$description['id'] = $result['ID'];
$description['value'] = $result['busname'] ;
array_push($return_arr,$description);
}
else
{
$description['id'] = $result['ID'];
$description['value'] = $result['lastname'] . ", " . $result['firstname'] ;
array_push($return_arr,$description);
}
}
}
echo json_encode($return_arr);
Edited with fix suggested below and entire syntax
This is a query from an autocomplete search box. So when someone types in a client or business client name, it uses this query to search the database and then displays the results using jquery.
The fix below works but when I do a search on a business client it is returning []. A client search works fine.
You could use two seperate query's and join them together like so:
SELECT * FROM clients
WHERE lastname LIKE "%agencyid%"
UNION
SELECT * FROM busclients
WHERE busname LIKE "%$agencyid%";
You sql syntax shoul look like this :
SELECT * FROM clients c
inner join
busclients b
on c.agencyid=b.idbus
WHERE (c.lastname and b.busname LIKE '$q%') AND c.agencyid = '$agencyid'
Just to complete the circle make sure you read this article on how to join tables in mysql

Database table join displays multiple entries of same rows when I only want one

I am doing a table join on a mysql databse.
I want the results to display just once but it displays each time there is an entry matching the query.
Here is what I have so far:
$descquery = "SELECT streams.name, streams.desc, users.streamnumber FROM streams, users WHERE users.streamnumber = '$_POST[streamnumber]' AND users.streamnumber = streams.name";
$result = mysql_query($descquery) or die(mysql_error());
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
echo $row['name']. " - ". $row['desc'];
echo "<br />";
}
This prints out multiple entries of what I want. Just wondered if theres something im doing wrong?
You have to use the DISTINCT clause, like this:
SELECT DISTINCT streams.name, streams.desc, users.streamnumber FROM streams, users WHERE users.streamnumber = '$_POST[streamnumber]' AND users.streamnumber = streams.name
Try this:
SELECT DISTINCT s.name, s.desc, u.streamnumber
FROM streams s INNER JOIN users u
ON u.streamnumber = '$_POST[streamnumber]'
AND u.streamnumber = s.name
Remember you MUST always sanitize user input before using it in a query to avoid sql-injection.

NHibernate CreateSqlQuery and addEntity

The hibernate manual says this:
String sql = "SELECT ID as {c.id}, NAME as {c.name}, " +
"BIRTHDATE as {c.birthDate}, MOTHER_ID as {c.mother}, {mother.*} " +
"FROM CAT_LOG c, CAT_LOG m WHERE {c.mother} = c.ID";
List loggedCats = sess.createSQLQuery(sql)
.addEntity("cat", Cat.class)
.addEntity("mother", Cat.class).list()
Now, what I have is basically the same. I am return two of the same type per row. I am doing a select something like this:
SELECT {ctrl1.*}, {ctrl2.*} FROM tableA AS A
LEFT JOIN tableB AS ctrl1 ON (A.controlID = ctrl1.controlID AND ctrl1.controlOptionType = ? AND ctrl1.controlOptionValue = ?)
LEFT JOIN tableB AS ctrl2 ON (A.controlID = ctrl2.controlID AND ctrl2.controlOptionType = ? AND ctrl2.controlOptionValue = ?)
And then I addEntity("ctrl1", typeof(mycontrolclass) and
addEntity("ctrl1", typeof(mycontrolclass)
Which seems exactly the same to me as their example. But I get this exception:
"Could not execute query" and the inner exception is "Could not find specified column in results".
If I copy the sql in the exception(to which it has added "AS ctrl1_1_3_3_" etc) it works fine.
Thanks.
What exactly are you trying to do? I believe you might not need using either of them.
// Using HQL:
var motherId = 25;
var hql = "select c.birthDate, c.mother from Cat c where c.mother.Id = :motherId";
var result = Session.CreateQuery(hql)
.SetParameter("motherId", motherId)
.ToList();
// Using NHibernate.LINQ:
var result = (from cat in Session.Linq<Cat>()
where cat.Mother.Id == motherId
select new { cat.birthDate, cat.mother }).ToList();
HQL query examples.
LINQ for NHibernate examples.
I dealt with your problem just for studying purposes, because you will surely
have found a solution in the meanwhile, but the problem should not lie in
the query (which is ok), but in some mapping inconsistency or somewhere else
(perhaps Database).