Combining two columns on a id - mysql

this is my database
database schema http://slashdir.com/php/blogg/images/bloggdb.png
What i want to do, is, for a given userid, show the total times he has been reported.
I have read various other questions on the matter, but I'm still stumped.
The latest query i tried was
select
sum(posts.timesreported + comments.timesreported) AS total_reports
FROM
posts
INNER JOIN comments ON (posts.userid = comments.userid)
WHERE posts.userid=5 AND comments.userid=5;
But this must be wrong as the number i get is much too high
Thanks!

SELECT
CASE WHEN NULL
THEN 0
ELSE (select sum(posts.timesreported) AS total_posts_reports
FROM posts INNER JOIN users ON (posts.userid = users.id)
WHERE posts.userid=5)
END
+
CASE WHEN NULL
THEN 0
ELSE (select sum(comments.timesreported) AS total_comments_reports
FROM comments INNER JOIN users ON (comments.userid = users.id)
WHERE comments.userid=5)
END
FROM DUAL;

Instead of
sum(posts.timesreported + comments.timesreported) AS total_reports
try
sum(posts.timesreported) + sum(comments.timesreported) AS total_reports
and I think you need to group by userId

WHERE posts.userid=5 AND comments.userid=5; is unnecessary since the tables are joined.
And sum operator is not correct logically
Use this query
select
sum(posts.timesreported) + sum(comments.timesreported) AS total_reports
FROM
posts
INNER JOIN comments ON (posts.userid = comments.userid)
WHERE posts.userid=5

It looks like your collecting the sum PRIOR to singling out the user. Perhaps this is adding those column values for all users prior to the join? What happens if you SELECT *, perform your INNER JOIN where userid = 5. Save the column values as two variables and then try to add them. Do you get the same result?
This might help you error check to see if the above theory is accurate.
<?php
// Connects to your Database
mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());
//Run Query
$NUM1=mysql_query("SELECT Field1 FROM Table WHERE user.key=5");
$NUM2=mysql_query("SELECT Field2 FROM Table WHERE user.key=5");
//Print Each Result
echo 'Num1 = '.$NUM1;
echo 'Num2 = '.$NUM2;
//Print Total
$TOTAL = $NUM1 + $NUM2;
echo 'Total = '.$TOTAL;
?>

Related

How can (SUM) in pivot table field and searching that field in yajra-laravel-datatable package (laravel 5.6)

! have three table
inventories
enter image description here
warehouses
enter image description here
inventory_has_warehouses
enter image description here
I have use laravel yajra datatable. i need sum and search of starting_balance this field in inventory_has_warehouses pivot table
my code:
$id = Auth::user()->id;
$row = Inventory::with('contact')->with('warehouse')
->select(
'inventories.*',
DB::raw('SUM(inventory_has_warehouses.starting_balance) as total')
)
->leftJoin('inventory_has_warehouses', 'inventory_has_warehouses.inventory_id', '=', 'inventories.id')
->leftJoin('warehouses', 'warehouses.id', '=', 'inventory_has_warehouses.warehouse_id')
->where('inventories.subscriber_id',$id)
->groupBy('inventories.id');
$datatable = DataTables::of($row)
->filterColumn('total', function($query, $keyword) {
$query->whereRaw('sum(inventory_has_warehouses.starting_balance) like ?', ['%'.$keyword.'%']);
})
return $datatable->make(true);
but i fount this type of error
Exception Message:↵↵SQLSTATE[HY000]: General error: 1111 Invalid use
of group function (SQL: select count() as aggregate from (select
inventories., SUM(inventory_has_warehouses.starting_balance) as
total from inventories left join inventory_has_warehouses on
inventory_has_warehouses.inventory_id = inventories.id left
join warehouses on warehouses.id =
inventory_has_warehouses.warehouse_id where
inventories.subscriber_id = 2 and inventories.status = 1 and
(LOWER(inventories.itemcode) LIKE %1% or
LOWER(inventories.purchasedescription) LIKE %1% or exists (select
* from contacts where inventories.supplier = contacts.id and LOWER(contacts.name) LIKE %1%) or
(sum(inventory_has_warehouses.starting_balance) like %1%)) group by
inventories.id) count_row_table)
mysql query
select inventories., SUM(inventory_has_warehouses.starting_balance)
as total from inventories left join inventory_has_warehouses on
inventory_has_warehouses.inventory_id = inventories.id left join
warehouses on warehouses.id = inventory_has_warehouses.warehouse_id
where inventories.subscriber_id = 2 and inventories.status = 1 and
(LOWER(inventories.itemcode) LIKE %1% or
LOWER(inventories.purchasedescription) LIKE %1% or exists (select *
from contacts where inventories.supplier = contacts.id and
LOWER(contacts.name) LIKE %1%) or
(sum(inventory_has_warehouses.starting_balance) like %1%)) group by
inventories.id
$id = Auth::user()->id;
$row = DB::table('inventories')->select('inventories.*','contacts.name',DB::raw('SUM(inventory_has_warehouses.starting_balance) as total'))
->leftJoin('contacts', 'inventories.supplier', '=', 'contacts.id')
->leftJoin('inventory_has_warehouses', 'inventories.id', '=', 'inventory_has_warehouses.inventory_id')
->where('inventories.subscriber_id',$id)
->groupBy('inventory_has_warehouses.inventory_id');
if ($keyword = $request->get('search')['value']) {
$row->having(DB::raw('SUM(inventory_has_warehouses.starting_balance)'), 'like', '%'.$keyword.'%');
$row->orHaving('inventories.itemcode', 'like', '%'.$keyword.'%');
$row->orHaving('inventories.purchasedescription', 'like', '%'.$keyword.'%');
$row->orHaving('contacts.name', 'like', '%'.$keyword.'%');
}
$datatable = DataTables::of($row)
->filterColumn('total', function($query, $keyword) {
})
return $datatable->make(true);
try to group by inventory_has_warehouses.inventory_id
Edited answer:
Your really giving hardtime for someone to read your query and give you help but to correct your query here is a reformatted query with corrections:
SELECT
inventories.*,
SUM(inventory_has_warehouses.starting_balance) as total
FROM
inventories LEFT JOIN inventory_has_warehouses
ON
inventory_has_warehouses.inventory_id = inventories.id LEFT JOIN warehouses
ON
warehouses.id = inventory_has_warehouses.warehouse_id
WHERE
inventories.subscriber_id = 2
AND
inventories.status = 1
AND
(LOWER(inventories.itemcode) LIKE '%1%' or LOWER(inventories.purchasedescription)
LIKE '%1%' OR EXISTS
(SELECT
*
FROM
contacts
WHERE
inventories.supplier = contacts.id
AND
LOWER(contacts.name) LIKE '%1%')
OR
(SUM(inventory_has_warehouses.starting_balance) LIKE '%1%')) GROUP BY inventories.id
the problem with query you sent is your like statement only have this:
LIKE %1%
this statement expects strings and it only says:
inventories.
this should be specific to a column you need or just use inventories.* to display all columns of that table but the error still doesn't make sense because it says and:
select count() as aggregate
maybe one of those would solve but upon reformatting your code I notice firstly the syntax error but this is very basic maybe you can start on just running a very simple query for the moment this might be the query that would work for you:
SELECT
inventories.id AS inventory_id,
warehouses.id,
SUM(inventory_has_warehouses.starting_balance) AS total
FROM
inventories LEFT JOIN inventory_has_warehouses
ON inventories.id = inventory_has_warehouses.inventory_id
LEFT JOIN
warehouses
ON warehouses.id = inventory_has_warehouses.warehouse_id
GROUP BY
inventory_has_warehouses.inventory_id
from this start adding the conditions one by one until the error appears again (do this on mysql query window not through laravel code) not yet sure how laravel handles sql queries but the format you sent will really cause an error and also if your going to post a question here make sure to make it reader friendly or someone might slam you cause its hard to read a code that is not properly formatted. ;)
also one thing I forgot make sure that the inventories.id is the primary key of that table or this will still cause you an error refer to this link for more details https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html

JOIN on keys that don't have the same value

I am trying to do an INNER JOIN on two tables that have similar values, but not quite the same. One table has a fully qualified host name for its primary key, and the other the hosts short name, as well as the subdomain. It it safe to assume that the short name and the subdomain together are unique.
So I've tried:
SELECT table1.nisinfo.* FROM table1.nisinfo INNER JOIN table2.hosts ON (table1.nisinfo.shortname + '.' + table1.nisinfo.subdomainname + '.domain.com') = table2.hosts.fqhn WHERE table2.hosts.package = 'somepkg';
This doesn't return the results I expect, it returns the first result hundreds of times. I'd like to return distinct rows. It takes a long time to run as well.
What am I doing wrong? I was thinking of running a subquery to get the hostnames, but I don't know what the right path from here is.
Thank you!
You can use group by in your query so you can achieve the desired results you want
please see this two links
Group by with 2 distinct columns in SQL Server
http://www.sqlteam.com/article/how-to-use-group-by-with-distinct-aggregates-and-derived-tables
Try putting your results into a temp table and then view the table to make sure that the columns are as expected.
SELECT table1.nisinfo.*, table1.nisinfo.shortname + '.' + table1.nisinfo.subdomainname + '.domain.com' AS ColID
INTO #temp
FROM table1.nisinfo;
Select *
from #temp INNER JOIN table2.hosts ON ##temp.ColID = table2.hosts.fqhn
WHERE table2.hosts.package = 'somepkg'
;
Put a Group By clause at the end of the second statement
So in this case, I used a subquery to get the initial results, and then used a join.
SELECT table1.nisinfo.* FROM table1.nisinfo JOIN (SELECT distinct(fqhn) FROM table2.hosts WHERE package = 'bash') AS FQ ON ((SUBSTRING_INDEX(FQ.fqhn, '.', 1)) = table1.nisinfo.shortname);

JOIN two sql SELECT statements where one has single record and other has multiple records

I have tow tables, the first is mda_alert_info and the second is key_contacts_info. For each alert set up there may be multiple corresponding contacts. Both tables are linked by 3 columns mda_id, stage_id and ref_number and during the query I will have to pass figures values for them
How do I get all what I want from both tables in one statement. Below are the individual SELECT statements.
$result = mysql_query("SELECT `mda_name`, `project_name`, `ipc_id` FROM `mda_alert_info` WHERE `stage_id`=1 AND `mda_id`=2 AND `ref_number`= '444'");
This will always return one record
$result = mysql_query("SELECT `contact_role`, `contact_email`, `contact_ph_number` FROM `key_contacts_info` WHERE `stage_id`=1 AND `mda_id`=2 AND `role`=0 AND `ref_number`='444'");
This may return multiple records
I tried for a while and couldn't get it to work so I tried adding another field called 'me' to both tables which is basically concatting mda_id and stage_id strings then I tried the query below.
$result = mysql_query("SELECT key_contacts_info.contact_role, key_contacts_info.contact_email, key_contacts_info.contact_ph_number, mda_alert_info.mda_name, mda_alert_info.project_name, mda_alert_info.ipc_id FROM key_contacts_info LEFT JOIN mda_alert_info ON key_contacts_info.me = mda_alert_info.me WHERE stage_id=1 AND mda_id=2 AND role=0 AND ref_number='444'");
But it's still not working. What am I doing wrong and how do I get it to work.
UPDATE:
Sorry but I should clarify something on the relationship between the tables the three columns exist on each table but are not primary keys on either of the tables
SELECT a.*, b.*
FROM mda_alert_info a
INNER JOIN key_contacts_info b
ON a.mda_id = b.mda_id AND
a.stage_id = b.stage_id AND
a.ref_number = b.ref_number
WHERE b.role = 0 AND
a.stage_id = 1 AND
a.mda_id = 2 AND
a.ref_number = '444'
To further gain more knowledge about joins, kindly visit the link below:
Visual Representation of SQL Joins
select
a.mda_name,
a.project_name,
a.lpc_id,
k.contact_role,
k.contact_email,
k.contact_ph_number
from mda_alert_info a
join key_contacts_info k
on a.state_id = k.state_id
and a.mda_id = k.mda_id
and a.ref_number = k.ref_number
where a.state_id = 1
and a.mda_id = 2
and a.ref_number = '444'
and k.role = 0
;

selecting "friends" with mySQL JOIN CASE

Here i posted a question about doing JOIN depending on the value of the column in the row.
You will need that is you make an Add Friend feature, where you write the ID of the 2 users who are Adding each other into user_1_id (my id) and user_2_id (friend id).
When you want to see who you are friends with, select DEPENDING on whether user_1_id or user_2_id has the ID of the surrent User (the one who is browsing)
I figured it out so down below is the query you want to use in case you need to do it.
Here is the query
$sql_inp = 'SELECT DISTINCT
users.id, users.first_name, users.last_name,
CASE
WHEN friends.user_2_id="'.$_SESSION[USER][id].'" //equal to current user id
THEN (SELECT friends.user_1_id FROM friends WHERE friends.user_2_id="'.$_SESSION[USER][id].'") // if user_2_id is My id, then fetch the other row
ELSE friends.user_2_id // obviously the opposite
END
FROM users
LEFT JOIN friends ON users.id= // this case is completely the same as one above
CASE
WHEN friends.user_2_id="'.$_SESSION[USER][id].'" THEN (SELECT friends.user_1_id FROM friends WHERE friends.user_2_id="'.$_SESSION[USER][id].'")
ELSE friends.user_2_id
END
WHERE friends.user_1_id="'.$_SESSION[USER][id].'" OR friends.user_2_id="'.$_SESSION[USER][id].'" // fetch the row where the either one of the values is equal to My id
';
Hope this helps if anyone had trouble
Personally, I hate using CASE statement. It makes queries look cluttered. Try using the IF function
$sql_inp = 'SELECT
table1.val1,table1.val2,
table2.val1,table2.val2,
IF(table3.val1="'.$user_id.'",table3.val1,
IF(table3.val2 ="'.$user_id.'",table3.val2,
IFNULL(table3.val2,-1))) users_fetch
FROM table1
INNER JOIN table2 ON table2.val1=table1.val1
LEFT JOIN table3 ON table2.val1=users_fetch';
In this query, if table3.val1 and table3.val2 <> $user_id, then users_fetch is -1.
Give it a Try !!!

Row counting a JOINed column without affecting the returned rows?

It's a bit difficult getting my problem into a short form, so I apologise if the title doesn't make sense.
Anyway, here is the problem:
$query = '
SELECT issues.*, comments.author AS commentauthor, favorites.userid AS favorited FROM issues
LEFT JOIN comments ON comments.issue = issues.id AND comments.when_posted = issues.when_updated
LEFT JOIN favorites ON favorites.ticketid = issues.id AND favorites.userid = \'' . $_SESSION['uid'] . '\'
' . $whereclause . '
ORDER BY issues.when_updated ' . $order;
Don't mind the fact that it's PHP as I am not asking for PHP help.
The query retrieves a bunch of issues, and what I'm wishing to do is obtain the row count of favorites that have favorites.ticketid matching issues.id. My use of LEFT JOIN favorites is not to get what I've just mentioned, but instead to obtain whether the client has favourited the issue, thus the part favorites.userid AS favorited.
I have tried doing the following: (all at once, I'm putting this in bulleted form for readibility)
duplicating the existing LEFT JOIN favorites and removing the user id check from the duplicate
adding , COUNT(favorites.ticketid) AS favoritescount to the SELECT section
adding AS favorited to the original LEFT JOIN as well as changing favorites.userid to favorited.userid
With that attempt, my query ends up returning only one row.
SELECT issues.*,
comments.author AS commentauthor,
favorites.userid AS favorited,
(
SELECT COUNT(favorites.id)
FROM favorites
WHERE ticketid = issues.id
) AS numfavorites
FROM issues
LEFT JOIN comments
ON comments.issue = issues.id
AND comments.when_posted = issues.when_updated
LEFT JOIN favorites
ON favorites.ticketid = issues.id
AND favorites.userid = ?uid
That should work, I'm just using a subquery to get number of favourites